Jayden Lawson
Jayden Lawson

Reputation: 2266

My php echo statements do not output expected array contents from SQL query

I have the following code which selects ID's of a database with many regions in it. I create the array as follows:

$old2 = $this->query("SELECT regionid FROM theregions WHERE regionparent = '808'");
$old2_array = mysqli_fetch_array($old2);

And then I try and output the array like so:

while($row = mysqli_fetch_array($old2)) {
    echo $row[0] . '<br>';
}

It produces the following:

800
834
933

However, if I use phpMyAdmin and run the same SQL statement, I get:

604
800
834
933

If I try using print_r(array_values($old2_array)); I get:

Array ( [0] => 604 [1] => 604 )

Have searched many SO pages, and have tried this:

$length = count($old2_array);
for ($i = 0; $i < $length; $i++) {
  echo $old2_array[$i], "<br />";
};

...which produces:

604

Notice: Undefined offset: 1 in /index.php on line 128

Upvotes: 2

Views: 70

Answers (2)

Jayden Lawson
Jayden Lawson

Reputation: 2266

The answer is not to have that second line. Once I remove this:

$old2_array = mysqli_fetch_array($old2);

Then the following loop works:

while( $reg = $old2->fetch_object() ) {
    echo $reg->region_id . "<br>";
}

For some reason, the mysqli_fetch_array() statement screws with following commands.

Upvotes: 0

milton cedeno
milton cedeno

Reputation: 58

I understand that php echo do not handles arrays directly but you have to use a syntax that includes curvy brackets if Im right. if I were you, I would use php var_dump(array_here) or load the array variable into a single variable first before echo it

Upvotes: 1

Related Questions