Weird behaviour when using PHP mysqli row - php

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

Related

end() expects parameter 1 to be array - php

I'm retrieving the email list from a MySQL database along side with the IDs of the users it gets something like this
Array (
[0] => Array ( [ID] => 1 [Email] => email1 )
[1] => Array ( [ID] => 2 [Email] => email2 )
)
and while trying to test for the value of the last email "email2" I used
end(end($array_sample));
this used to work on my old server running PHP 5.0 and stopped at the new one running PHP 5.6
Was there something I did wrong or is it a php version?
I basically changed the whole approach to get the site to do what it was meant to do any how, but I still would like to learn about the end(end(array)) issue.
end() function needs to get array by reference, so it can't be a result of other function, because you get following error:
Only variables should be passed by reference
To avoid it assign result of inner end() to variable and then use end() on this variable:
$tmp = end($array);
$result = end($tmp);
And you probably don't get any error in previous version of PHP due to error_reporting set to quiet them.
According to documentation:
Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you
would have to explicitly enable this kind of error level in PHP <
5.4.0.
As far as I know, your code should had never worked:
Only variables should be passed by reference
As documentation explains:
This array is passed by reference because it is modified by the
function. This means you must pass it a real variable and not a
function returning an array because only actual variables may be
passed by reference.
What has changed is the severity of the error. It has been a fatal error, a strict standards notice and a regular notice. Between 4.3.0 and 5.0.4 is just failed silently.
Most likely the error went unnoticed until you upgraded and an actual error message was triggered.
You have an end within another end, the inner one returns last element of array, the outer one is expecting an array not a single value

best way append named array to array in PHP 5.2

I got used to this notation for creating empty arrays and add named elements to them when needed;
$array = [];
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
Now I learned that the [] notation for arrays does not work in older versions of PHP, like PHP 5.2.
Instead I have to do;
$array = array(
"error" => array()
);
array_push($array["error"], "new error message as element 0 of $array['error']");
This way is a little bit inconvenient in my case because the great thing about the first code snippet is that the "error" entry in $array is only created when there is an actual error, whereas in the latter case the entry (although empty) exists either way.
Is there a way to get similar 'functionality' (i.e. specifying/adding named elements when needed, not at initialisation) in a way that is also easily readable in PHP 5.2?
EDIT:
The first code snippet in the original post was reading $array = array[];. The author corrected it after I posted this answer.
The first code snipped is incorrect. There is no such thing as array[]. The correct syntax is array().
$array = array();
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
You don't have to worry about PHP versions. This syntax always worked on PHP since its dawn and it will probably work forever. Keep using it.
The first way of creating array in PHP is incorrect. This syntax works in PHP5.2 below too, so you dont need to worry about it. You don't need to use array_push and simply do following.
The correct syntax is:
$array = array(); // notice it doesn't to array[]
// add error when there is one
$array["error"][] = "new error message as element 0 of $array['error']";

Cannot access PHP Object as Array

I am facing a strange problem. It may just be a silly mistake, and I am just missing some basics.
I'm running php 5.6.1 on MAMP.
I have a simple array which I get from a mysql query. Using a foreach loop, I can print_r() each value, which gives me: stdClass Object ( [srno] => 6 [link] => this-is-link )
Now I can echo $obj->srno, and that prints fine. But I can't use echo $obj['srno'] which I was previously using, on an older version of PHP, but- It shows nothing.
Any help really appreciated. Thanks!
If you have a stdClass object and need to address it as an array, you can cast it to array quite easily:
$someObj = new stdClass();
$someObj->foo = "bar";
$someArray = (array)$someObj; // Cast the object to an array
echo $someArray['foo']; // Will give you "bar"
Working example: http://3v4l.org/nni1Y
Of course as comments already pointed out, you may want to look at retrieving your mysql results as an array in the first place.
As you said your results return as an object so you can use it by using
$obj->your_field_name to display field value. But your can not use by $obj['field_name'];

array_keys error while running artisan basset

I am receiving the proceeding error exception when I run php artisan basset --tidy-up from the command line.
[ErrorException]
array_keys() expects parameter 1 to be array, object given
basset [--delete-manifest] [--tidy-up]
I was unfortunate in finding any details online.
Although I've not used Basset, the reason for this error is that you are passing in an object, rather than an array, for the first argument of array_keys.
For example, were I to have an array as follows:
$myGreatArray = array('first' => 'foo', 'bar' => 'sup');
And then pass it in to array keys:
print_r(array_keys($myGreatArray));
I'd get this as the output:
Array
(
[0] => first
[1] => bar
)
However, I can't do the same thing with an object, even if it's structured the same way.
In other words, we can't do something like this (and not just because you need to var_dump objects, but also because you need to pass in arrays to array_keys()):
$myGreatArray = new stdClass;
$myGreatArray->first = 'foo';
$myGreatArray->bar = 'sup';
print_r(array_keys($myGreatArray));
You'll get an error similar to what you're seeing, although what you're seeing appears to be in a format of an exception handled by Basset. You can also see it when running a script from other than the command line, depending on your level of error reporting.
Edit:
I just pulled up the source for Basset's command line script, and it looks like you're getting the error on line 120, which reads as follows:
$collections = array_keys($this->environment->all()) + array_keys($this->manifest->all());
You might want to check the way your manifest and environment are structured.

Size of array in codeigniter, native PHP function support

As per documentation, I've tried below code to find size of array in codeigniter
echo element('size', $get, NULL);
but it ended up showing following error
( ! ) Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\cinifb_ci\system\helpers\array_helper.php on line 46
I've tried to load content of $get into another array variable, but it continued showing the above error.
Please suggest me the alternative ways along with solving this.
I've tried to using native PHP solutions like
echo size_array($get);
but It ended up in
Fatal error: Call to undefined function size_array()
Does this mean I'm not supposed to use native PHP functions in CodeIgniter
count($array);
That's the native function to get the size of an array ;)
Within CodeIgniter, this expression:
element('size', $get, null)
Only works if $get is an array and it has an index 'size'; if it is an array, it would be more likely that you meant this:
count($get);
However, in your case, $get is actually an object, stdClass to be exact; determining the size of that object requires another step:
count(get_object_vars($get));
Example:
$completed_requests = $this->db->where('status' => SOLICITACAO_FINALIZADA)
->where('trip_occurred' => OCORREU)
->count_all_results('transport_requests');
->count_all_results('TABLE_NAME');

Categories