Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql / PDO - Setting Variable

Tags:

mysql

pdo

I'm having trouble trying to set a variable then use it in a select statement. I keep getting a "general error" and can't figure out what I'm doing wrong. Any input would be appreciate. I'm trying to set a variable using subqueries with named parameters.

$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();
like image 872
Ralph Avatar asked Feb 14 '23 18:02

Ralph


1 Answers

If you want to use MySQL user variables, for some reason, you don't need multi-queries support. They (user variables) live as long as you session (connection) is open. Therefore you can do something like this

$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);

Sample output:

array(1) {
  [0]=>
  array(1) {
    ["@available"]=>
    string(6) "100.00"
  }
}
like image 170
peterm Avatar answered Feb 17 '23 09:02

peterm