I want to store all rows of a column name returned as a mysql query result in a string array. I am new to php. I have retrieved the rows but how do I store all rows of a column in an array? I mean how to iterate the counter of rows and store the column in an array? Or is there any direct function/method call? Please see my code below and its possible ways of storing in an array:
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'users';
mysql_select_db($dbname);
$result = mysql_query("SELECT users.email FROM users");
// AND THEN FINALLY STORING IN A STRING ARRAY:
$array = $result;
// OR SOMETHING LIKE:
Store($array, $result);
// OR SOMETHING LIKE:
for(int i = 0; i < $result.Rows.Count; i++)
{
if (null != $row[0])
{
$array[i] = $result[i];
}
}
// OR SOMETHING LIKE:
while($null != result.read())
{
$array.Add($result.Read());
}
Please help me in writing the code.
$result = mysql_query("SELECT users.email FROM users");
while($row = mysql_fetch_array($result)){
$array[] = $row;
}
This will return an array of associated arrays. The $row
will contain the index of the column name along with integer index.
For example:
echo $row['email'];
//or
echo $row[0];
In the end you can get the first row by:
$array[0]['email']; //or $array[0][0];
NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead.
This is how you can do it
$rec = mysqli_query("SELECT users.email FROM users");
$data = array();
$i=0;
while($row = mysql_fetch_assoc($rec)){
$data[$i]['column1'] = $row['column1_from_table'];
$data[$i]['column2'] = $row['column2_from_table'];
$data[$i]['column3'] = $row['column3_from_table'];
}