Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Populating an Array from a MySql Query

Tags:

php

mysql

I am looking to create an array of data to be pass to another function that is populated from a database query and am not sure how to do this.

$dataArray[0][1];

$qry = mysql_query("SELECT Id, name FROM users");

while($res = mysql_fetch_array($qry)) {
    $dataArray[$res['Id']][$res['name']]
}

Thanks in advance.

like image 200
aHunter Avatar asked Nov 20 '09 07:11

aHunter


2 Answers

This would look better

$dataArray = array();

$qry = mysql_query("SELECT Id, name FROM users");

while($res = mysql_fetch_array($qry)) {
    $dataArray[$res['Id']] = $res['name'];
}

you can take a look at the PHP manual how to declare and manipulate arrays.

like image 110
RageZ Avatar answered Sep 24 '22 02:09

RageZ


The below code sniper is very handy...

$select=" WRITE YOUR SELECT QUERY "; $queryResult= mysql_query($select);

//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();

//STORE ALL THE RECORD SETS IN THAT ARRAY 
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC)) 
{
    array_push($data_array,$row);
}


mysql_free_result($queryResult);


//TEST TO SEE THE RESULT OF THE ARRAY 
echo '<pre>';
print_r($data_array);
echo '</pre>';

Thanks

like image 35
Surendra Narayan Roy Avatar answered Sep 25 '22 02:09

Surendra Narayan Roy