php - 从准备好的语句中获取数据

标签 php sql mysql mysqli prepared-statement

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

相关文章:

sql - Oracle SQL - DATE 大于语句

php - 从表单上的 Post 请求创建 SQL 表

mysql 手动递增 ids?

php - 在php中将数据库导出为pdf文件

java - 从 Google App Engine 中的 PHP 文件获取文件

php - 从mysql数据库表中选择 future 日期记录

具有唯一服务器和多个端口的 MySQL 表

mysql - 一组数据结构的变化类似于SVN?

php - 将 Windows-1256 转换为 UTF-8

php - Angular 4 - 如何使用参数将数据获取到数据库