![](/img/trans.png)
[英]How can I make a IF ELSE statement in PHP from a response of JSON?
[英]How can I make a JSON from a MySQL prepared statement in PHP?
我在PHP中有此代碼,在該代碼中,我試圖根據已准備好的語句的結果制作JSON。 問題是它返回的是完全白頁,什么也沒出現。
$con = mysqli_connect(HOST,USER,PASS,DB);
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
array_push($result,
array('Id'=>$tweetid,
'Body'=>$body,
));
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
我已經將$ tweetid和$ body的內容作為測試打印在while語句中,並且可以正常工作,這意味着問題不是查詢,而是數組的問題。 我想念什么?
謝謝!
這樣嘗試
$result = array();
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
演示: https : //3v4l.org/XZOu5
經過一些調試后,我發現了問題。 問題出在json_enconde函數中,由於JSON_ERROR_UTF8
錯誤類型,該函數默默地失敗了。 在使用JSON_UNESCAPED_UNICODE
之前,我曾遇到過來自本國語言的特殊字符問題,但是這次我添加了mysqli_set_charset($con, "utf8");
到代碼的頂部,現在可以正常工作了。 為了完整起見,該語言為巴西葡萄牙語。 完整的代碼如下。
$con = mysqli_connect(HOST,USER,PASS,DB);
mysqli_set_charset($con, "utf8");
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
感謝Barclick Flores Velasquez的幫助。 我是php的新手,我不知道有用於調試的print_r,它對找到解決方案很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.