4

我在尝试设置变量然后在 select 语句中使用它时遇到了麻烦。我不断收到“一般错误”,无法弄清楚我做错了什么。任何输入将不胜感激。我正在尝试使用带有命名参数的子查询来设置变量。

$query = $dbh->prepare("Set @available = (SELECT SUM(payments) FROM payments WHERE customer = :customer) - (SELECT SUM(charges) FROM charges WHERE customer = :customer); SELECT @available");
$query->bindParam(":customer", $customer);
$query->execute();
4

2 回答 2

8

如果你想使用 MySQL 用户变量,由于某种原因,你不需要多查询支持。只要您的会话(连接)打开,它们(用户变量)就会存在。因此你可以做这样的事情

$customer = 1;

try {
    $db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $sql = "SET @available = (SELECT SUM(payments) FROM payments WHERE customer = ?) - 
                             (SELECT SUM(charges)  FROM charges  WHERE customer = ?)";
    $query = $db->prepare($sql);
    $query->execute(array($customer, $customer));

    $query = $db->prepare("SELECT @available");
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Exeption: " .$e->getMessage();
    $result = false;
}
$query = null;
$db = null;

var_dump($result);

样本输出:

数组(1){
  [0]=>
  数组(1){
    [“@可用”]=>
    字符串(6)“100.00”
  }
}
于 2013-11-07T01:21:34.097 回答
0

PDO 似乎没有为多查询提供任何正式的支持(但似乎确实提供了一些支持),但mysqli确实提供了。但是,它们都不提供对准备好的多个语句的支持。

你可以mysqli这样使用:

$mysqli = new mysqli('servername', 'username', 'password', 'dbname');
$query = sprintf("Set @available = (SELECT SUM(payments) FROM payments WHERE customer = %1$s)" .
            " - (SELECT SUM(charges) FROM charges WHERE customer = %1$s);".
            " SELECT @available",
            $mysqli->real_escape_string($customer) );

 // Following code lifted from PHP Manual.
 // This code will read multiple results, if they're available.
 // Your query only returns one.

 /* execute multi query */
 if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

参考在这里

于 2013-11-07T01:11:42.923 回答