简体   繁体   中英

The Upgrade From PHP5 to PHP7 “Broke” Retrieving Array Values

Under PHP5 I was able to use an array ( $_SESSION['issuenum_index'] ) developed with the code below.

if ($_SESSION['mfilter'] == 0) {
    $query = "SELECT IssueIDNUM,MagazineNUM FROM tblIssueList ORDER by IssueDate DESC, IssueIDNUM ";
} else {
    $query = "SELECT IssueIDNUM,MagazineNUM FROM tblIssueList WHERE MagazineNUM = {$_SESSION['mfilter']} ORDER BY IssueDate DESC, IssueIDNUM ";
}           

$_SESSION['issuenum_index'] =$conn->query($query);

if (!$_SESSION['issuenum_index']) die($conn->error);

$_SESSION['rowcount'] = mysqli_num_rows($_SESSION['issuenum_index']);

Now that I have upgraded to PHP7, the array does not seem to work. The correct row count is returned, but the values for IssueIDNUM and MagazineNUM appear missing.

When I run the code below:

    foreach($_SESSION['issuenum_index'] as $key => $value)
    {
        echo $key." Value:  ". $value ."<br>" ;
    }

I get the result: "2181 Value: Array" . The number "2181" is the line number. Instead of the word "Array", I was expecting the values releated to " IssueIDNUM " and " MagazineNUM ".

When I run the following code: print_r($_SESSION['issuenum_index']); I get: "mysqli_result Object ( [current_field] => 0 [field_count] => 2 [lengths] => [num_rows] => 2187 [type] => 0 )" . I don't see the two field names.

How can the field names be displayed for this array? Also how can this code be fixed for PHP7?

The return of your $conn->query($query) is not an array, but mysql_result object which implements Traversable interface, so you can loop through it. [current_field] => 0 [field_count] => 2 [lengths] => [num_rows] => 2187 [type] => 0 are properties of this object. http://php.net/manual/en/class.mysqli.php .

So, while we iterating through this object it will return an array of data. "2181 Value: Array" - 2181 - is the key of your data array. I hope, you've got "218 0 Value: Array" above and so on till 0. Array is where your data is. Just try to print_r($value) and you will see, what is going on.

You could use fetch_all method ( http://php.net/manual/en/mysqli-result.fetch-all.php ) to set all the data inside you session (not asking, why are you doing so)

$_SESSION['issuenum_index'] = $conn->query($query)->fetch_all();

EDIT: Suggest that your previous PHP version was lower then 5.4, where Traversable interface was added. No deal with PHP7.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM