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条)

报告相同问题?