简体   繁体   中英

php Prepared Statement giving me JSON Malformed

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?

$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.

Try use

$outcome->num_rows;

OR

mysqli_stmt_num_rows($outcome);

Also use

$outcome->bind_result('userID','email', 'age', 'surname', 'forename');
$outcome->fetch()

instead

mysqli_assoc_fetch()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM