1

我有一个函数,它是从数据库中返回一个包含记录的行数组,这些记录是基于 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 循环。

4

2 回答 2

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().

于 2009-03-06T13:51:38.397 回答
1

"... LIKE ? ..."(而不是"... LIKE '%?%' ...")和$getRecords->bind_param("s", "%$searchString%");

于 2012-09-06T08:28:38.947 回答