简体   繁体   中英

Php Build an Array from MySQL

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

1maxpaynemax@hat.com24/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' => 'nick@moppy.com',
        'dob' => '11-01-1965',

    ),

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM