How to add SQL elements to an array in PHP
So this question is probably pretty basic.
I am wanting to create an array from selected elements from a SQL table.
I am cu开发者_如何学Gorrently using:
$rcount = mysql_num_rows($result);
for ($j = 0; $j <= $rcount; $j++)
{
$row = mysql_fetch_row($result);
$patients = array($row[0] => $row[2]);
}
I would like this to return an array like this:
$patients = (bob=>1, sam=>2, john=>3, etc...)
Unfortunately, in its current form, this code is either copying nothing to the array or only copying the last element.
Try this instead.
$patients = array();
while ($row = mysql_fetch_row($result)) {
$patients[$row[0]] = $row[2];
}
If it doesn't work, there's something wrong with your query.
you can use print_r()
here is an example
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
more here http://php.net/manual/en/function.print-r.php
How about this :
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$count=0;
while ($count < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $count);
$arr_row[$col -> $count] = $row[$col -> $count];
$count++;
}
But I not sure if this is what you are looking for, just guessing .. ount
精彩评论