Jump to content

[SOLVED] php array not storing results


phplearner2008

Recommended Posts

Dear all,

I have a code which runs a sql query, the results of which I would like to store in an array. The code is like this:

 

$sql = "SELECT * FROM profile where GENDER = 'F' ";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result))

{

    $MID[] = $row['MATRIMONIAL_ID'];

    echo "$MID[]";

}

 

echo "$MID[]" does not output anything whereas echo $row['MATRIMONIAL_ID']

spits out the results correctly.

I am using empty brackets $MID[] because I read that php will automatically assign values from 0 and increase it by 1. Why am I not able to store value in $MID[] array?

Can anyone tell me what mistake I am doing?

Thank you.

Link to comment
Share on other sites

The problem is that PHP does not know which element of the array you are trying to echo. You are correct that it can add to an array without specifying the key - it just uses the next available number. However, when you read from an array, you must specify the key.

 

If you're trying to echo something in the loop, use $row['MATRIMONIAL_ID'].

Link to comment
Share on other sites

Well, you've already shown how to store the results in an array with this line:

 

$MID[] = $row['MATRIMONIAL_ID'];

 

The point is that you cannot then echo a value without providing a key. Basically, if you wish to do anything with the variable inside the array then use $row['MATRIMONIAL_ID'].

 

If you do this:

 

$sql = "SELECT * FROM profile where GENDER = 'F' ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
     $MID[] = $row['MATRIMONIAL_ID'];
}
echo '<pre>'.print_r($MID,1).'</pre>';

 

You will see that the array has been populated.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.