我有一个函数,它返回一个包含来自数据库的记录的行数组,这些行是基于LIKE查询选择的。出于安全原因,我希望此查询是一个准备好的语句。显然我不能像我一样使用绑定参数和查询功能。我当然不确定如何让我将查询作为预备语句,并返回我想要返回的行。
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循环。
答案 0 :(得分:4)
如果您有很多专栏,虽然很乏味,但您可以这样做:
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()
。
答案 1 :(得分:1)
撰写"... LIKE ? ..."
(而不是"... LIKE '%?%' ..."
)和$getRecords->bind_param("s", "%$searchString%");