[英]fetching data from a prepared statement
我有一個 function,它返回一個包含數據庫記錄的行數組,該數組是基於 LIKE 查詢選擇的。 出於安全原因,我希望此查詢成為准備好的語句。 顯然我不能像我一樣使用綁定參數和查詢 function 。 那時我不確定如何將我的查詢保留為准備好的語句,並返回我試圖返回的行。
function getRowsByArticleSearch($searchString, $table, $max) {
$con = mysqli_connect("localhost", "x", "x", "x");
//global $con;
$recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
//$getRecords->execute();
echo "test if";
//$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
while ($getRecords->fetch()) {
$result = $con->query($recordsQuery);
$rows = array();
echo "test while";
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
return $rows;
} else {
print_r($con->error);
}
}
永遠不會進入 while 循環。
如果您有很多列,雖然很乏味,但您可以這樣做:
function getRowsByArticleSearch($searchString, $table, $max) {
$con = mysqli_connect("localhost", "x", "x", "x");
$recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE ? ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
$getRecords->execute();
$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
$rows = array();
while ($getRecords->fetch()) {
$row = array(
'ARTICLE_NO' => $ARTICLE_NO,
'USERNAME' => $USERNAME,
...
);
$rows[] = $row;
}
return $rows;
} else {
print_r($con->error);
}
}
本質上,您必須自己創建所需的關聯數組,因為您不能使用$result_set->fetch_assoc()
。
寫"... LIKE? ..."
(而不是"... LIKE '%?%'..."
)和$getRecords->bind_param("s", "%$searchString%");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.