1

So Ive got a couple of statements using a list of variables and it seems i am always adding another column to the database so i wanted to make one list of variables and contain it somehow so i can just change it once if i need to instead of half a dozen times.

    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($a, $b, $c, $d, $e, $f, $g);

$stmt->fetch();

$stmt->close(); 

But I want to make something like this:

    varList="$a, $b, $c, $d, $e, $f, $g";

    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($varList);

$stmt->fetch();

$stmt->close(); 
  • have you checked if bind_result() also can accept an array? if so, use an array containing all of your vars – Kristian Apr 06 '12 at 19:43
  • thanks Kristian, but i tried putting it in an array and bind doesnt seem to accept an array. I get the "doesnt match number of variables" error – killer on the road Apr 06 '12 at 19:45

1 Answers1

1

What you can do is make an array (of references to variables), and then use call_user_func_array to call bind_result.

Example:

$varList = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); // variable names.
$params = array(); // list of params

foreach($varList as $v){
    $params[] = &$$v; // store a reference to the vars in $params
}

call_user_func_array(array($stmt, 'bind_result'), $params);

You may not need that foreach loop, you may also be able to do this:

$varList = array(&$a, &$b, &$c, &$d, &$e, &$f, &$g); // variable references

call_user_func_array(array($stmt, 'bind_result'), $varList);

Based off this answer: https://stackoverflow.com/a/966717/206403

Community
  • 1
  • 1
gen_Eric
  • 223,194
  • 41
  • 299
  • 337