torsdag 1 april 2010

PHP 5.3 problems with references

Hi! I have recently updated to Ubuntu Lucid. With this I also got PHP 5.3.2. I thought it would be no problems updating PHP, but now after some hours for debugging I know I was wrong.

First I got a mysql SQLException (My own exception telling my about syntax error). And an warning:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in /var/www/bla/lib/classes/Database/MysqliStmt.class.php on line 68

This was confusing as SQL-syntax shouldn't change. It hadn't. I found that the SQLException was due to another query that returned nothing, and by this causing the other query to fail. The other problem with the warning was trickier. I have built an Database abstraction layer, and I'm using "call_user_func_array(array(&$stmt, 'bind_param'), $params);" in my mysqli-driver, on line 68.

This error was new, I have used my database abstraction layer several times on diffrent servers without any errors. I first tried to solve the problem by changing how $params is created.

From:

foreach($values as $value) {
$params[] = $value;
}

to:

foreach($values as $value) {
$params[] = &$value;
}

Problem solved, if my only aim was to get rid of warnings at least. I didn't get any results from my querys earlier, but now I still didn't get results but no errors or warnings either. When I printed out $params I could see that all values where the same, the last put into the array $params. Then after a while I realized what I was doing. "foreach" copies a value from $values to $value. If PHP is working with references (which 5.3.2 seems to do more), then I'm just placing references into $params to $value. And $value changes on every loop. This explains why all values in $params had the same value, the last entered into $params. The solution was to use this code:

for($i = 0; $i < $max; $i++) {
$params[$i+1] = &$values[$i];
}

Here I go thorugh $values. For each value in $values I put an reference into $params. The reference is pointing into the right position in the array $values.

Inga kommentarer:

Skicka en kommentar