Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an associative array from MySQL Query Results - PHP

Tags:

php

mysql

I am trying to create an associative array from MySQL query results. I would like to pull two columns, one contains names, another contains numbers. What I intend to create is something like:

$array = array('maggie'=> 68, 'Joseph' => 21, 'ireen'=> 64);

$dbc = mysqli_connect('localhost', 'root', 'password', 'newbie');
$query = "SELECT fname, eng_end FROM members_records";
$result = mysqli_query($dbc, $query);
while ($array = mysqli_fetch_assoc($result)) {
$data_array[] = $array[];
}

I am unable to construct something sensible between curly braces that can create an array with data from the name column as keys and data from the numbers column as values. Every effort within the curly braces was handsomely rewarded with long and angry PHP parse errors.

How would I proceed from there, or is my foundation too faulty to lead to anything? How best can my goal be accomplished (with minimum code, if possible)?

like image 880
Bululu Avatar asked Jun 04 '11 01:06

Bululu


1 Answers

You probably want something like this:

$dbc = mysqli_connect('localhost', 'root', 'password', 'newbie');
$query = "SELECT fname, eng_end FROM members_records";
$result = mysqli_query($dbc, $query);
$data_array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data_array[$row['fname']] = $row['eng_end'];
}

Substitute your actual column names for 'name' and 'value'.

like image 188
dkamins Avatar answered Sep 28 '22 10:09

dkamins