【问题标题】:mysql query looped with results stored in an arraymysql 查询循环,结果存储在数组中
【发布时间】:2012-08-14 16:37:47
【问题描述】:

我有一个正在处理的运输模块,我正在尝试查询一个 mysql 表,计算 PO 上给定行项目的行数,并将结果存储在一个数组中。我认为我不能在 mysql 中进行分组,因为它不会为没有任何发货的订单项提供结果。目的是获取原始订单数量,通过我的查询计算发货的单位数量,然后从原始数量中减去发货的单位,以提供要根据该订单项发货的剩余单位。

为了确保我什至收到零数量的没有装运的行项目并将其存储在数组中,我试图循环我的查询并将每个单个结果作为一个值存储在我的数组中。如果有更好的方法,我愿意接受有关改变方法的建议。

这是我的查询:

// I have a previous query that provides the number of line items for a given po.  that number is stored in variable $num1 
$a=1;
$LiShipped = array();

while($a<$num1){

$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$LiShipped[] = mysql_fetch_array($query2);
$a++;
}

不幸的是,当我遍历我的数组时,似乎数组中没有存储任何内容。

<?php
echo $LiShipped[0]; //results nothing
echo var_dump($LiShipped); // results array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL }
?>

看起来都是空值。

【问题讨论】:

  • 这可能无助于回答您的问题,但您应该停止使用mysql_* 函数。它们正在被弃用。请改用PDO(PHP 5.1 起支持)或mysqli(PHP 4.1 起支持)。如果您不确定要使用哪一个,read this article.

标签: php mysql arrays loops


【解决方案1】:

在尝试检索结果之前,您需要执行查询(通过调用mysql_query()):

$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$query2 = mysql_query( $query_2); // <-- NEED THIS
$LiShipped[] = mysql_fetch_array( $query2);

请注意,以上省略了 SQL 查询的基本错误检查和清理以防止 SQL 注入。

【讨论】:

    【解决方案2】:

    你没有执行你的查询,它不能工作。试试这个代码:

    // I have a previous query that provides the number of line items for a given po.  that number is stored in variable $num1 
    $a=1;
    $LiShipped = array();
    
    while($a<$num1){
        $query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
        $res = mysql_query($query2);
        while($LiShipped[] = mysql_fetch_array($res));
        $a++;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2016-11-18
      • 2022-08-03
      • 1970-01-01
      • 2013-08-05
      • 2023-03-17
      • 2016-10-29
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多