duandai2178 2016-02-21 10:54
浏览 46
已采纳

php Prepared Statement给我JSON格式错误

My php code works fine when it is not a prepared statement - however when it is a prepared statement it is giving me a json malformed error. After debugging my code for some time I have realised that there is something wrong with my if statement and that it should be different when it is a prepared statement. I am not sure what to change but this is my code:

$statement = "SELECT userID, forename, surname, email, age FROM employees WHERE forename = ?"
$outcome = $conn -> prepare($statement);
$outcome->bind_param('s', $forename);
$outcome->execute();
$outcome->close();
$outcomearray = array();
echo json_encode("It works as of now"); // This bit works and the message is echoed

// From this point, it is giving me errors and problems
if(mysqli_num_rows($outcome)){
    while($line = mysqli_fetch_assoc($outcome)){
        $outcomearray[] = array
        (
            "userID" => $line["userID"],
            "forename" => $line["forename"],
            "surname" => $line["surname"],
            "username" => $line["username"],
            "email" => $line["email"],
            "age" => $line["age"]
        );
    }
    echo json_encode($outcomearray);
}

It is the following two lines:

 if(mysqli_num_rows($outcome)){
        while($line = mysqli_fetch_assoc($outcome)){

that I believe are giving the errors.

How do I fix this?

  • 写回答

2条回答 默认 最新

  • douyuefei3546 2016-02-21 11:09
    关注
    $stmt = $conn->prepare(
      "SELECT userID, forename, surname, email, age FROM employees WHERE forename = ?"
    );
    $stmt->bind_param('s', $forename);
    $stmt->execute();
    $rows = array();
    $result = $stmt->get_result();
    
    while($line = $result->fetch_assoc()){
      $rows[] = $line;
    }
    
    print json_encode($rows);
    
    $conn->close();
    

    Note that this is the typical pattern when you are returning JSON resonses. If there is no match you render an empty array - thus there is no real need to check the number of rows.

    If you for whatever reason needed to you can get the number of rows from the num_rows property on the mysqli_result object:

    $result = $stmt->get_result();
    
    if ((bool) $result->num_rows) {
    
    }
    

    Also note that the whole point of fetch_assoc is to get an associative array. So if your column names line up with the JSON you want to produce there is no need to map the keys one by one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于温度改变石墨烯介电性能(关键词-介电常数)
  • ¥150 HDMI分路器LT86102 的输出在890MHz频点处EMC超标8DB
  • ¥15 druid(相关搜索:数据库|防火墙)
  • ¥15 大一python作业
  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥60 如何鉴定微信小程序数据被篡改过
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥20 手机截图相片分辨率降低一半