【问题标题】:Prepared statements for MySQL from PHP (with mysqli)从 PHP 为 MySQL 准备的语句(使用 mysqli)
【发布时间】:2012-10-03 07:59:24
【问题描述】:

我在 MySQL 数据库中有这些表:

CREATE TABLE `product` (
`idProduct` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
PRIMARY KEY (`idProduct`)
);

CREATE TABLE `sale` (
`idSale` int(10) unsigned NOT NULL AUTO_INCREMENT,
`highDate` date NOT NULL,
`idProduct` int(10) unsigned NOT NULL,
`idUser` varchar(45) NOT NULL,
PRIMARY KEY (`idSale`)
);

我想获得一个表格,其中包含行中的用户和列中的产品,例如这个问题: MySQL Pivot row into dynamic number of columns

SQL Fiddle (Demo) 中工作正常,但我需要帮助才能使用 mysqli 从 PHP 中查询它。

这是正确的吗?

$this->dbh->query("SET @sql = NULL");
$stmt = $this->dbh->query("SELECT GROUP_CONCAT(DISTINCT
                          CONCAT(
                          'count(case when category = ''',
                          category,
                          ''' then 1 end) AS ',
                          replace(category, ' ', '')
                       )
                    ) INTO @sql
                FROM product;");

$stmt = $this->dbh->prepare("SET @sql = CONCAT('SELECT s.idUser, ', @sql, ' FROM sale s
                            LEFT JOIN product p ON p.idProduct = s.idProduct
                            GROUP BY s.idUser');");

$stmt->execute();

如何从查询中检索数据? Execute() 方法返回 TRUE 或 FALSE。

【问题讨论】:

    标签: php mysql mysqli prepared-statement


    【解决方案1】:

    使用它来获取结果

    while ($stmt->fetch()) {
        //code
    }
    

    http://php.net/manual/en/mysqli-stmt.fetch.php

    【讨论】:

    • 好的,谢谢!问题是:我怎么知道列数?要使用fetch()我需要在bind_result($column1, $column2,...)之前做但是我不知道有多少列检索到查询。
    【解决方案2】:

    最后我做了以下事情:

    $query = $this->dbh->query("SELECT GROUP_CONCAT(DISTINCT CONC...");
    $result = array();
    $row = $query->fetch_row();
    
    $query = $this->dbh->query("SELECT " . $row[0] . " FROM sale s ...");
    return $query->fetch_array(MYSQLI_ASSOC);
    

    【讨论】:

      【解决方案3】:

      您可以使用$stmt->fetch$stmt->get_result() 从查询语句中检索结果,如下所示:

      fetch()

      while ($stmt->fetch()) {
          printf ("%s (%s)\n", $name, $code);
      }
      

      get_result()

      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_array(MYSQLI_NUM)) {
          foreach ($row as $r) {
              print "$r ";
          }
          print "\n";
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-04-16
        • 2015-03-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 2011-06-20
        相关资源
        最近更新 更多