Reputation: 764
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',
),
Upvotes: 0
Views: 87
Reputation: 4187
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.
Upvotes: 1
Reputation: 6297
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>";
Upvotes: 0
Reputation: 5849
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);
}
Upvotes: 1