使用数组操纵检索的数据

时间:2012-02-25 22:19:11

标签: php mysql

我正在查询数据库如下:

$result=mysql_query("SELECT name,items FROM mytable WHERE user_id='$id'");

现在,我想创建一个数组来插入作为此查询结果的值e'g让我们说这是结果数据:

name    quantity
john    10
joel    20
brian   10
  1. 如何使用$ name和$ quantity作为变量创建一个数组来插入上述数据;
  2. 其次,(这是一个交易平台),所以假设一个用户想要从数组中的数据中购买25个项目,因此要实现这一点,脚本必须从john获取10个项目,从joel获取15个项目(最多加起来25),然后将他们的项目设置为剩余的值,即john的项目= 0和joel的项目= 5.我如何编码this.please协助。我试图尽我所能简化这个。谢谢

1 个答案:

答案 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()进行限制!