如果你想使用 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”
}
}