我的json代码没有显示任何内容,我已经尝试了很多代码,但没有任何帮助。
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.n";
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
echo json_encode($json); //empty?!
sqlsrv_free_stmt( $stmt);
这有许多可能的问题:
1(您是否检查过查询是否实际返回行?
2(您循环数据两次(两次while( $row = sqlsrv_fetch_array...
循环(,这既无用又无效。
3(the do...while ( sqlsrv_next_result($stmt) );
子句也应该是不必要的,因为fetch_array会知道什么时候到了数据的末尾,而你只有一个结果集,所以你不需要在它们之间移动
4(您正在回显原始数据和JSON,因此,如果您对此脚本进行ajax调用,它将失败,因为响应将部分包含非JSON数据
我认为这足以为您提供一些合理的数据:
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
如果这有效:
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
其余的也必须工作。
正如艾迪森所说:
if( $stmt === false)
{
echo "Error in query preparation/execution.n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
要仔细检查,请在此代码中添加您的回显,如下所示:
if( $stmt === false)
{
echo "Error in query preparation/execution.n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
$json[] = $row;
}
echo json_encode($json);
如果此代码有效,请接受 ADyson 答案
这是解决问题的一种方法。希望你的查询写得很好。
$dataFinal= array();//final variable that will contain total array for json
for($k=0;$k<count(variable_that_contents_the_resutl_array_query);$k++){
$ligne = array("item_id"=> $row['item_id'],
"item_name"=>$row['item_name'],"Barcode"=> $row['Barcode']);
array_push($dataFinal, $ligne);//add line in array datafinal
}//end for loop
$result = array($dataFinal);
$response = new Response(json_encode($dataFinal));
$response->headers->set('Content-Type', 'application/json');
return $response;