2

Using PDOStatement::bindParam(), one can bind a parameter to a variable—which is especially useful when a prepared statement is executed multiple times, each with different parameter values. For example:

$dbh = new PDO('mysql:dbname=foo', 'eggyal', 'password1');
$qry = $dbh->prepare('DELETE FROM bar WHERE qux = ?');
$qry->bindParam(1, $qux, PDO::PARAM_INT);

while (true) {
  $qux = ... ;
  $qry->execute();
  // etc
}

My questions are:

  1. Is it possible to bind a parameter to the member variable of an object? For example:

    $qry->bindParam(1, $obj->qux, PDO::PARAM_INT);
    
  2. If so, to which object's member variable is such a parameter bound: that which is referenced at the time of the bindParam() call, or that which is referenced upon statement execution? For example:

    $obj->qux = 123;
    
    $obj = new stdClass();
    $obj->qux = 456;
    
    $qry->execute();  // which value is used for qux ?
    
  3. Where is this behaviour documented (if at all)?

eggyal
  • 122,705
  • 18
  • 212
  • 237
  • 2
    It's bound to an instance property of the object at binding time. Creating a new object and assigning it to the previous objects variable name will not update the reference. – mario Dec 29 '12 at 01:02
  • Agreed. If you are saving multiple objects to the DB in one go, might I suggest rewriting this inside a transaction? (if your engine supports it.) – FredTheWebGuy Dec 29 '12 at 01:11

1 Answers1

5

PHP stores the reference of the variable to use it. When you call $qry->bindParam(1, $obj->qux, PDO::PARAM_INT), the reference stored is the reference of the member of the instanciated class.

When you change the member $obj->qux, the reference is still the same than the one stored in your $obj. However, if you reinstanciate $obj to a new class, then every references are changed, but your old object is still in memory ! So when you assign a new value to the new $obj->qux, it is not the same variable used, so running $qry->execute will use the old value.

I hope I've been clear enough.

Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33