0

I currently collect data like this :

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    echo $row['id'].$row['name'].$row['surname'].$row['email'].$row['dob'];
    echo "<br />";
}

It outputs all the data in one line, like this

[email protected]/07/1950

I want to build the data into a Array rather so it looks like this :

$fields = array(
        'id' => '21890',
        'name' => 'nick',
        'surname' => 'moppy',
        'email' => '[email protected]',
        'dob' => '11-01-1965',

    ),
4
  • You're half-way through it, just replace your array values with the proper variables and you're done. And actually, $row is already the original array you are looking to build. Commented Jun 8, 2015 at 12:37
  • 1
    $row is already an array Commented Jun 8, 2015 at 12:39
  • 1
    Pass MYSQL_ASSOC into mysql_fetch_array and that's what you're after isn't it in $row? Commented Jun 8, 2015 at 12:40
  • Do you need $fields array with only values for id, name, etc.. or whole table? Commented Jun 8, 2015 at 12:55

3 Answers 3

1

You already have your array:

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    var_dump($row);
}
Sign up to request clarification or add additional context in comments.

Comments

1

So I'm going to make an assumption here. That is that you only want id, name, surname, email and dob. If you want all the columns returned from the table and in the array, just return the SELECT to what it was.

$query = "SELECT id, name, surname, email, dob FROM applicants";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    // $row is now what your example array looks like
}

So there are 2 differences, first, the specified columns from the table. If you're actually wanting all of the columns returned (back to using * for example), but don't want all of the columns returned in your array, this won't work (but you haven't said either way) but @b0s3 first example will.

Second, the addition of the MYSQL_ASSOC parameter. This tells PHP to return an array with only the column name indicies as opposed to them AND numeric keys which doubles up the number of items in the array.

Comments

0

You should use this way.

$query = "SELECT * FROM applicants";

$result = mysql_query($query) or die(mysql_error());

 while($row = mysql_fetch_assoc($result)){
   $res[] = $row;

 }
echo "<pre>"; print_r($res);   echo "</pre>";

2 Comments

no need to use that now as var_dump will do that work
@D4V1D It is not exactly the same. Its better.

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.