8

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

1
  • shouldn't it be $data_array[] = $array;? Also: $data_array is not defined. Commented Jun 4, 2011 at 1:26

2 Answers 2

27

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'.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @dkamins, I added correct DB credentials and made substitutions for column rows and it works like a charm!
substitute your column names for name and value?? So, using the OPs example, you're saying it should be $data_array[$row['fname']] = $row['eng_end'] ????
0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.