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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测