簡體   English   中英

mysqli用while循環准備語句

[英]mysqli prepared statement with while loop

我正在嘗試使用 mysqli 進行非常簡單的查詢。 它快把我逼瘋了!

我只希望$data是來自 sql 查詢的值的數組。

這是我的代碼...

$req = $app->request();
$hashtag = $req->get('hashtag');

require_once 'Slim/lib/database.php';

$db = connect_db();

$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = '%#' . $hashtag . '%';
$statement -> bind_param("s", $newhashtag);

$statement -> execute();

$statement -> bind_result($result);

while ( $row = mysqli_fetch_array($statement) ) {
    $data[] = $row;
}

print_r($data);

$statement -> close();

我只是得到一個錯誤mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given並且在fetch_array上使用$result$statement沒有區別

你可以試試這個:

$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = "%#$hashtag%";
$statement->bind_param("s", $newhashtag);
$statement->execute();
$result = $statement->get_result();

while ($row = $result->fetch_assoc())
{
    $data[] = $row;
}

這使用get_result()函數,該函數用於從准備好的語句中獲取結果。

這在 while 循環之外初始化並分配給一個新變量,在本例中$result
然后$result->fetch_assoc()被分配給$row並且可以在循環內訪問。 將每一列作為數組中的鍵訪問,這樣$row["content"]將返回該列下每一行的內容

要從准備好的語句中獲取結果對象,您可以使用get_result() 然后可以使用foreach循環迭代該對象。

$statement->execute();

$result = $statement->get_result();

foreach ($result as $row) {
    print_r($row);
}

如果需要將所有行提取到數組中,可以使用fetch_all()

$statement->execute();

$result = $statement->get_result();

$data = $result->fetch_all(MYSQLI_ASSOC);
print_r($data);

您還可以通過將每列綁定到一個變量來獲取數據。 首先,使用bind_result()指定要填充的變量,然后調用fetch()來填充該變量。

$statement->execute();

$statement->bind_result($content);

while ( $statement->fetch() ) {
    // Every time fetch is called a value from the next row will be inserted into $content
    $data[] = $content;
}

print_r($data);

替換這些行:

while ( $row = mysqli_fetch_array($statement) ) {
   $data[] = $row;
}

用這些:

while ($row = $statement->fetch()) {
   $data[] = $row;
}

暫無
暫無

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

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