使用PHP mysqli行时的奇怪行为

I am currently translating a PHP script from a PHP server of version 5.4 to a PHP server with version 5.3

I immediately noticed a wierd behaviour in our login script.

After analysing the script for a bit, I found the source of the problem.

A call to a member of the first row in $result->fetch_row was invaild.

The declaration of $result is shown below:

$username = $mysqli->real_escape_string(strtolower($_POST["USERNAME"]));
$password = $mysqli->real_escape_string(md5(strtolower($_POST["PASSWORD"])));

$result = $mysqli->query("SELECT * FROM $table WHERE username='$username' AND password='$password'");

By instinct I checked if I had called the data_seek properly, however; I had.

Printing out the fetch_row() function gave me the following result

Array ( [0] => 3 [1] => admin [2] => d76362b0f640fbcf869033b5e4d1c4bf [3] => Mr [4] => Rasmus [5] => 4 [6] => [7] => 0 )

The array was therefore working.

But the following declaration did not work.

$Title = $result->fetch_row()[3];

Therefore I tried to store the entire row in a single array object, and then call all sub members individually.

Like so:

$row = $result->fetch_row();
$Title = $row[3];

And it worked perfectly.

How come? What is wrong with this declaration:

$Title = $result->fetch_row()[3];

The ability to reference the elements of a returned array directly from the calling method is introduced in PHP 5.4 - which is why it's not working in 5.3.

From Example #7 on http://php.net/manual/en/language.types.array.php

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

So your temporary solution looks like it will become a long-term one :)

You said you were translating the script from PHP 5.4 to PHP 5.3. Apparently you forgot that line because

$Title = $result->fetch_row()[3];

is not valid PHP 5.3. You should get an error reading:

Parse error: syntax error, unexpected '[', expecting ',' or ';' in ...

Notes

As you can see in the release notes of PHP.net

functionname()[1] is something what has been added in PHP 5.4.

it is not possible to dereference the result of a function call directly in PHP 5.3 and later versions but as of PHP 5.4 it is possible