[英]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.