Page 1 of 1

PHP questions.

Posted: Wed Jul 08, 2009 1:09 am
by valrangel
I got this php code at the end of my php file, but I got and error that says:
Notice: Undefined variable: array_multi in C:\wamp\www\getPets.php on line 52

$j = 1;
while ($row=mysqli_fetch_assoc($result))
{
foreach ($row as $colname => $value)
{
$array_multi[$j][$colname] = $value;
}
$j++;
}
return $array_multi;
}
?>

But I do not know why I am getting this error..
Thanks!!

Re: PHP questions.

Posted: Wed Jul 08, 2009 1:12 am
by SvanteH
Have you declared $array_multi before using it?

Code: Select all

<?php
  //Causes notice
  echo $test;
  
  //Does not cause a notice
  $think = "hello";
  echo $think;
?>
It will automatically try declaring the variable if it doesn't exist from before but the notice is just as a warning incase you e.g misspelt a variable name.

Re: PHP questions.

Posted: Wed Jul 08, 2009 2:10 am
by iamngk
what SvanteH telling is correct. you need to declare following line just before the while loop

$array_multi = array();

Re: PHP questions.

Posted: Wed Jul 08, 2009 2:28 am
by VladSun
In fact, it's the $array_multi[$j] which also should be initialized:

Code: Select all

$array_multi[$j] = Array();
foreach ($row as $colname => $value)
{
$array_multi[$j][$colname] = $value;
PS:

In PHP you can use the

Code: Select all

$array[] = $value;
which is the same as

Code: Select all

$array[count($array)] = $value;
or

Code: Select all

array_push($array, $value);
this way variable $j in some cases is made redundant.

PPS: $row is an associative array, so you can grab the whole of it and add it to the results array:

Code: Select all

while ($row = mysqli_fetch_assoc($result))
    $array_multi[] = $row;
return $array_multi;