如何从PHP中的MySQL预处理语句中创建JSON?

时间:2017-08-26 02:49:44

标签: php mysql json

我在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语句中作为测试,它工作正常,这意味着问题不是查询,而是数组的问题。我错过了什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个

 $result = array();
 while(mysqli_stmt_fetch($stmt)){
       $result[] = array('Id'=>$tweetid,'Body'=>$body);
    }

演示:https://3v4l.org/XZOu5

答案 1 :(得分:0)

经过一些调试我发现了问题。问题出在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用于调试,它帮助了很多人找到了解决方案。