[英]Prepared statements for MySQL from PHP (with mysqli)
我在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將數據透視表的行轉換成動態的列數
在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。
您可以使用$stmt->fetch
或$stmt->get_result()
從查詢的語句中檢索結果,如下所示:
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
最后,我執行了以下操作:
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.