首页 > 解决方案 > sql准备语句重新调整空json数组

问题描述

我有 3 个单选按钮,当我选择其中一个时,我希望从相应的表中加载下拉列表,所以我声明了变量$choice来保存单选按钮的状态并分配 2 个新变量$table来设置表的名称我将获取数据和另一个$secolumn来设置每个表的列名,然后使用准备好的语句连接到 mysql DB

<?php
include "connect.php";//to connect to the mysql DB
$table ='';
$secolumn ='';
if (isset($_GET["table_cond"])) {
    $choice = $_GET["table_cond"];
    if ($choice == "table_fixe") {
        $table = "cr002t_cours_fixe";
        $secolumn ="CR002_DEV_DIN";
    } elseif ($choice == "table_billets") {
        $table = "cr004t_cours_billet";
        $secolumn = "CR004_DEV_BILLC";
    } elseif ($choice == "table_itqb") {
        $table = "cr005t_cours_intbq_comp";
        $secolumn = "CR005_DEV_COMP";
    } else {
        echo "choose a button";
    }
}

$sql ="SELECT DISTINCT GR027DEVISE, GR027LIB 
        FROM gr027t_devises D, ".$table." T 
        WHERE D.GR027DEVISE = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo"sql statement failed";
}else {
    mysqli_stmt_bind_param($stmt, "s", $secolumn);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
}
$currency_array=[];
while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['GR027DEVISE'];
    $name = $row['GR027LIB'];
    $currency_array[] =array("id"=>$id,"name"=>$name);
}
echo json_encode(['currency_array'=>$currency_array]);
?>

然后在前端,当在其中一个单选按钮/下拉列表 id sel_curr_name 的 id 上单击时,我添加了以下脚本

<script type="text/javascript">
function checkTABLE(table_cond){
    var sel_curr_name=document.querySelector('#sel_curr_name');
    var content='';
    
    $.ajax({
        type:'get',
        url :'/myfolder/getcurrencylist.php?table_cond='+table_cond,
        success:function(data){
            json=JSON.parse(data);
            console.log(json.currency_array);
            $.each( json.currency_array, function( key, value ) {
                content+='<option value='+value.id+'>'+value.name+'</option>'
                });
                sel_curr_name.innerHTML=content;
        }
    })
}

当我选择按钮时浏览器控制台中的问题我得到一个空数组=>,在网络选项卡中我得到这个 {"currency_array":[]}

标签: phpmysqljson

解决方案


推荐阅读