我在mysql中有6个查询,我需要一次性使用php执行。我怎么能这样做。?

时间:2018-02-28 04:54:52

标签: php mysql

我有多个SQL查询,它们共同创建了一个数据透视表。现在我想使用PHP运行此查询。我尝试使用PDO运行它,但它返回错误。

这是我写的PHP代码

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "logs";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $ex) {
    die($ex->getMessage());
}

$query = "start transaction;
SET @sql = NULL;
SET @@group_concat_max_len = 5000;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
        'MAX(IF(cropname = ''',
        cropname,
        ''', quantity, NULL)) AS ''',
        cropname,''''
    )
) INTO @sql
FROM
    tempcrop;

SET @sql = CONCAT('SELECT date, SUM(quantity),', @sql, ' FROM tempcrop Group By date');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    commit;";

$stmt = $conn->prepare($query);
$stmt->execute();

$cropData = array();

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    $cropData['AllCrops'][] = $row;
}
    echo json_encode($cropData);
?>

运行此代码会给我一个错误

  

&#39;致命错误:未捕获的异常&#39; PDOException&#39;消息&#39; SQLSTATE [HY000]:一般错误&#39;

如何改为运行这些查询?

0 个答案:

没有答案