aHunter
aHunter

Reputation: 3530

PHP Populating an Array from a MySql Query

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.

Upvotes: 5

Views: 17038

Answers (2)

Surendra Narayan Roy
Surendra Narayan Roy

Reputation: 49

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

Upvotes: 3

RageZ
RageZ

Reputation: 27323

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.

Upvotes: 6

Related Questions