Home » Php » Creating an associative array from MySQL Query Results – PHP

Creating an associative array from MySQL Query Results – PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

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)?

How to&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['name']] = $row['value'];
}

Substitute your actual column names for ‘name’ and ‘value’.

Answer:

An associative array is created like this:

$a = array('foo' => 'bar', 'color' => 'green');

You can add keys after its creation like this:

$a['someotherkey'] = 'value';