我正在查询数据库如下:
$result=mysql_query("SELECT name,items FROM mytable WHERE user_id='$id'");
现在,我想创建一个数组来插入作为此查询结果的值e'g让我们说这是结果数据:
name quantity
john 10
joel 20
brian 10
答案 0 :(得分:0)
mysql_fetch_assoc是你的朋友:
// Better turn on error_reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
// sp@20120227 - added the ')' at the end of the condition in the where part
$cursor = mysql_query( 'SELECT name,items '
. ' FROM mutable '
. ' WHERE ( user_id = "' . mysql_real_escape_string( $id ) . '" ) '
);
$foundItems = array();
// likely to be a parameter of a function...
$totalUnitsOrdered = 25;
// maps user to amount assigned from him
$assignedQuantityPerUser = array();
while ( $row = mysql_fetch_assoc( $cursor ) ) {
// Still order Quantity left?
if ( 0 < $totalUnitsOrdered ) {
if ( $row[ "items" ] <= $totalUnitsOrdered ) {
// assign all of $row[ "items" ]
$totalUnitsOrdered -= 0 + $row[ "items" ];
$assignedQuantityPerUser[ $row[ "name" ] ] += 0 + $row[ "items" ];
} else {
// assign all the rest: $totalUnitsOrdered
$totalUnitsOrdered = 0;
$assignedQuantityPerUser[ $row[ "name" ] ] += $totalUnitsOrdered;
}
}
$newItem[] = $row[ "name" ];
$newItem[] = $row[ "items" ];
// Append $newItem to the end of $foundItems
$foundItems[] = $newItem;
} // while
重要提示:切勿将用户输入数据直接传递给查询。始终使用mysql_real_escape_string()
进行限制!