Mysql / PDO - 设置变量

时间:2013-11-07 00:29:13

标签: mysql pdo

我在设置变量时遇到问题,然后在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();

2 个答案:

答案 0 :(得分: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);

示例输出:

array(1) {
  [0]=>
  array(1) {
    ["@available"]=>
    string(6) "100.00"
  }
}

答案 1 :(得分: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());
}

引用为here