Jump to content

Adding Array Members in a While loop


amilaik

Recommended Posts

Hi all,

 

I'm trying to write a function to return an array. But it keeps returning an empty array with NULL values ....

 

This is my code.

 

 

function ShowUserData ($uid)

{

$con = mysql_connect("localhost","user","pass");

if (!$con)

{

die('Oops !! something went wrong with the DB connection, Server said ' . mysql_error());

}

 

mysql_select_db("db", $con);

 

$password = md5($password);

 

$query = mysql_query("SELECT * FROM `table` WHERE `uid` = '".$uid."'");

$num = mysql_num_rows($query);

 

while ($row = mysql_fetch_array($query, MYSQL_NUM)) {

  $outArray = array('uid' =>$row['uid'], 'email' => $row['email'], 'name' => $row['name']); 

}

return $outArray;

}

 

what am i doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/226104-adding-array-members-in-a-while-loop/
Share on other sites

You are asking for a numeric array, and trying to assign associative indexes.

 

Change your while loop to:

    
      while ($row = mysql_fetch_assoc($query)) {
          $outArray[] = $row;  //IF you only expect 1 row, you don't need a while loop, and you don't need the brackets on $outArray.
      }

looks like a scoping issue, but even if you get that to work, you're still only going to get the last returned row in the array. try something like this:

 

$outArray = array();
while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
    $outArray[] = array('uid' =>$row['uid'], 'email' => $row['email'], 'name' => $row['name']); 
}
return $outArray;  

 

so you're essentially returning an array of arrays. you can loop through them like this:

 

foreach ($outArray as $row) {
    // do something with the row elements (e.g. $row['uid'])
}

 

something like the above cures both issues.

looks like a scoping issue, but even if you get that to work, you're still only going to get the last returned row in the array. try something like this:

 

$outArray = array();
while ($row = mysql_fetch_array($query, MYSQL_NUM)) { //<--STILL PULL NUMERICAL ARRAY
    $outArray[] = array('uid' =>$row['uid'], 'email' => $row['email'], 'name' => $row['name']); //<--STILL TRYING TO ASSIGN ASSOC INDEXES
}
return $outArray;  

 

 

Before you go any further, lets do some de-bugging.

 

Top of script:

echo '<pre>'; print_r($_REQUEST); echo '</pre>';

 

Change query call to:

$query = mysql_query("SELECT * FROM `table` WHERE `uid` = '".$uid."'") or die(mysql_error());

 

And of course as Indicated above.

 

Change your fetch call:

//Either:
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
//or
while ($row = mysql_fetch_assoc($query)) {

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.