我在投资表中有多行。我需要检索所有这些并使用json_encode
将其发回
这是我的代码
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
while($x1 = mysql_fetch_array($result))
{ $detail = $x1['detail'];
$sector = $x1['sector'];
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
在javascript中我编写了以下脚本:
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('display_acc.php',{id:value},function(data)
{
data = JSON.parse(data);
$( '#a' ).html(data.a);
$( '#b' ).html(data.b);
});
});
我的问题是它只返回最后一行的数据。我想收到所有行的数据。
我必须在id a and b
显示{{1}}
我用表来显示它。
提前感谢
答案 0 :(得分:1)
你需要循环中的数组
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
$cnt=0;
while($x1 = mysql_fetch_array($result))
{ $detail[$cnt] = $x1['detail'];
$sector[$cnt] = $x1['sector'];
$cnt++;
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
并在javascript循环结果
答案 1 :(得分:1)
这应该可以解决问题:
- OP解释后编辑 -
<强> PHP 强>
$project_code = (int)$_GET['id']; //better put (int) before to avoid SQL Injection
$sql = "select detail, sector from investment where project_code = '$project_code'"; //better to maintain if you set only the fields you will use
$result = mysql_query($sql);
$return = array('detail'=> array(), 'sector' => array()); //here you can put empty return array or set detail and sector key. Your choice will have impact in your front-end
$return['my_extra_var' ] = $my_extra_var;
$i = 0;
while($x1 = mysql_fetch_array($result))
{
$return['table'][$i]['detail'] = $x1['detail'];
$return['table'][$i]['sector'] = $x1['sector'];
$i++;
}
echo json_encode($return);
<强>的Javascript 强>
... your ajax request ...
data = JSON.parse(data);
var tableData = data.table;
$.each(tableData, function(index, value) {
$('#tableData').append('<tr><td>'+value.detail+'</td><td>'+value.sector+'</td></tr>'); //append row to tbody
});
<强> HTML 强>
<table>
<thead>
<th>Details</th>
<th>Sector of Investment</th>
</thead>
<tbody id="tableData">
</tbody>
</table>
答案 2 :(得分:0)
看起来你没有积累这两个元素。尝试这样的事情:
array_push(your_array_name, $detail, $sector);
然后在完成所有操作后对数组进行编码。