phplearner2008 Posted September 19, 2008 Share Posted September 19, 2008 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. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted September 19, 2008 Share Posted September 19, 2008 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']. Quote Link to comment Share on other sites More sharing options...
phplearner2008 Posted September 19, 2008 Author Share Posted September 19, 2008 GingerRobot, I am trying to extract the results in an array so that i can use it later on. Can you expand your idea on how i should store it in an array? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted September 19, 2008 Share Posted September 19, 2008 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. Quote Link to comment Share on other sites More sharing options...
phplearner2008 Posted September 19, 2008 Author Share Posted September 19, 2008 Now it's working Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.