簡體   English   中英

mysqli stmt准備不工作

[英]mysqli stmt prepare not working

我完全不知道這里出了什么問題。 在其他部分中,相同的確切說明也適用。

只是嘗試制作一個簡單的准備好的select語句並將其加載到數組中。

mysqli表現得很奇怪,幾乎是出於隨機原因而崩潰/工作的。

$id = 1;
$s_user = 1000;

$hold = array();
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt,"SELECT article_id, title, summary, body, category_id, tags FROM articles WHERE article_id = ? AND user_id = ?")){

    mysqli_stmt_bind_param($stmt, "ii", $id, $s_user);
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_bind_result($stmt, $article_id, $title, $summary, $body, $category_id, $tags); 

   while(mysqli_stmt_fetch($stmt)){
    $hold[] = array(
        'article_id'    => $article_id,
        'title'         => $title,
        'summary'       => $summary,
        'body'          => $body,
        'category_id'   => $category_id,
        'tags'          => $tags
            );
     }       
}

更新:嘗試過mysqli_errno,如果失敗則在結尾放置else語句。 mysqli_stmt_bind_result是問題所在(應注意,這是if語句失敗的地方)。 如果我刪除該功能,它將起作用。

我也嘗試過mysqli_stmt_get_result,但是沒有運氣。 還有其他想法嗎?

以下是我的編寫方式,因為它更易於編寫和調試。 您需要mysqlnd才能使用此代碼樣式,但是默認情況下應在PHP 5.4和更高版本中啟用它。

$sql = "SELECT article_id, title, summary, body, category_id, tags FROM articles
    WHERE article_id = ? AND user_id = ?";
if (($stmt = $con->prepare($sql)) === false) {
    trigger_error($con->error, E_USER_ERROR);
}
if ($stmt->bind_param("ii", $id, $s_user) === false) {
    trigger_error($stmt->error, E_USER_ERROR);
}
if ($stmt->execute() === false) {
    trigger_error($stmt->error, E_USER_ERROR);
}
if (($result = $stmt->get_result()) === false) {
    trigger_error($stmt->error, E_USER_ERROR);
}
$hold = $result->fetch_all(MYSQLI_ASSOC);

看到? 無需綁定也無需循環。 最終結果是$hold包含一個關聯數組的數組,如您所願。

您應該始終檢查錯誤的返回值,至少對於prepare()execute() 每次。 還有其他可能的mysqli方法,如果出現錯誤,幾乎所有方法都會返回false。

問:如何使用$ hold? 是否像這個$ hold ['username']一樣?

來自@Phil的評論,是的,我們可以啟用異常報告功能,但是我通常不把這個選項放在那兒,因為大多數與mysqli掙扎的PHP開發人員可能尚未准備好處理異常。 但是使用異常很好,因為您不必編寫所有重復的錯誤檢查代碼。

激活異常:

$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

暫無
暫無

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

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