簡體   English   中英

PHP的准備好的聲明給我JSON格式錯誤

[英]php Prepared Statement giving me JSON Malformed

我的php代碼不是prepared statement時可以正常工作-但是,當它是預備語句時會給我一個json malformed error 在調試我的代碼一段時間后,我意識到我的if語句出了點問題,當它是prepared statement時應該有所不同。 我不確定要更改什么,但這是我的代碼:

$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);
}

它是以下兩行:

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

我相信是在犯錯誤。

我該如何解決?

$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();

請注意,這是返回JSON共振時的典型模式。 如果沒有匹配項,則呈現一個空數組-因此,實際上不需要檢查行數。

如果出於任何需要,可以從mysqli_result對象的num_rows屬性獲取行數:

$result = $stmt->get_result();

if ((bool) $result->num_rows) {

}

還要注意,fetch_assoc的重點是獲得一個關聯數組。 因此,如果您的列名與要生成的JSON對齊,則無需一一對應地映射鍵。

試試用

$outcome->num_rows;

要么

mysqli_stmt_num_rows($outcome);

也用

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

代替

mysqli_assoc_fetch()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM