Why is fetch_array $Row is an array inside while loop, but NULL below while loop?

Hello;

I am working on a website for baseball game schedules.

The PHP Manual says that mysql_fetch_array is deprecated and that for new development the use of the MySQLi functions are recommended.

I have elected to use the object oriented style (shown below).

I am assigning the fetch_array $Result to the $Row variable. If I put gettype($Row) inside the while loop it says that the type for $Row is array.

However, if I put gettype($Row) just below the closing bracket for the while loop it says the type for $Row is NULL.

I am using $Rows as $Key => $Row in a foreach loop and it is working fine.

I have two questions:

Question 1. Why does gettype($Row) say that the $Row variable is an array while inside the while loop; and then say that the $Row variable is NULL immediately below the closing bracket for the while loop?

Question 2. Am I using proper coding technique using the $Row variable in the foreach loop or should I be using $Value, like $Rows as $Key => $Value, in the foreach loop?


// Run a query
$Query = "SELECT ...";

// Assign query to result variable
$Result = $MySQLi -> query($Query);

// Loop through all the records in the result
// Assign each table row array to $Row array
while($Row = $Result -> fetch_array())
{
	// Assign $Row array to $Rows array
	$Rows[]			=	$Row;

echo gettype($Row); // says "array array array array"
}
echo gettype($Row); // says NULL

// foreach loop using previous array $Row works fine!
foreach($Rows as $Key => $Row)
{
	echo $Row[0]; // Works great! Prints out all the values in table first column.
		}


Thanks.

You elect to use object notation, but for some reason then decide to access the results as an array, which on the face of it makes little sense.

You then take the array of results and assign them to yet another array using $Rows array notation.

So when you use gettype well, that is telling you that you have an array of arrays - which is what you just did above.

The db returns an array of results, which contains arrays, then you assign it to another array.

I don’t know why gettype $row returns null.

If you like the object notation (->) and you have no other cause to use arrays then you could access your result set as objects too as seen in this code from the manual:


<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\
", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\
", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

If you are doing lots of array comparisons with your results then fetching arrays is a good thing, but otherwise I learned early on (after frequently visiting nested array hell myself ;)) that using the object notation wherever possible is a) easier to read (for me) b) easier to use in double quotes (you dont need to concat strings and c) really gets you into the mode of thinking about OOP.


// this is less error prone, less typing, easier to scan
echo "I live in $obj->Country now.";
//vs
// than this
echo "I live in " . $row['Country'] . " now";

Cups;

Thanks for respond to my question.

I am just now starting to learn about the MySQLi. I didn’t even realize that the mysql functions have been replaced with the mysqli ones.

From what I can tell the mysqli method has been going on since abot 2006. I wished I had known about it earlier. I have made a couple of web sites since then.

Here’s a page on the PHP Manual I found that tells about the thre APIs:
http://hu.php.net/manual/en/mysqlinfo.api.choosing.php

It’s going to take me a while to get comfortable with this mysqli method. But you’ve got to start somewhere.

Thanks again.

I hate it when people make assumptions about sample code posted by users, and then never answer the actual question. It’s happened to me on every board I’ve ever been on.

Ok, Volitics, here’s your answer…



// EX: I want you to fetch the next row
// then do whatever is in the loop, but only
// if there WAS a next row to fetch.

// What it means is that, at some point
// fetch_array will return null because
// there are no more rows to return

while($Row = $Result -> fetch_array())
{

    // this is ok, because we are inside the loop
    // the only to GET inside the loop is if
    // fetch_array succeeded, which means
    // we have a valid row
    echo gettype($Row);

}

// this one will be null because this 'Row'
// was generated on the last repitition of
// the while loop, meeting the condition
// to exit the loop
echo gettype($Row);


If you need a linear explanation…



// assume $results has 3 records...

// pointer is now on record 1

$row = get_a_row($results);
if ($row != null) { do_something_with_row($row); } // this is called
if ($row == null) { exit_out(); }

// pointer is now on record 2

$row = get_a_row($results);
if ($row != null) { do_something_with_row($row); } // this is called
if ($row == null) { exit_out(); }

// pointer is now on record 3

$row = get_a_row($results);
if ($row != null) { do_something_with_row($row); } // this is called
if ($row == null) { exit_out(); }

// pointer is now beyond the end of the recordset

$row = get_a_row($results); // returns null
if ($row != null) { do_something_with_row($row); }
if ($row == null) { exit_out(); } // this is called



I hope that helps you visualise how the while loop works.

Serenarules;

That does help.

Thanks.

Yeah, since about then.

It was introduced with PHP5. With 5.1 PDO came bundled too, and for a long time there was much debate about which was best for a given situation.

See [google]PDO vs Mysqli[/google]

I had already plumped for PDO because I found an class written for PHP4 which did a reasonable job emulating the main benefits of what would be the future PDO.

I normally have to ignore questions about mysqli because I have never used it except when boning up on the diffs between PHP4 and PHP5.

One of the main benefits of using either of these methods is to be able to use prepared statements which help to protect your database from sql injection attacks. Once you have got your head around how they work I’m sure you will find you are writing cleaner code. I frankly find PDOs prepared statements easier to use and I prefer its API.