我有一个函数,它是从数据库中返回一个包含记录的行数组,这些记录是基于 LIKE 查询选择的。出于安全原因,我希望此查询成为准备好的语句。显然我不能像我一样使用绑定(bind)参数和查询功能。那时我不确定如何将我的查询保留为准备好的语句,并返回我试图返回的行。
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()
.
关于php - 从准备好的语句中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/618902/