【问题标题】:php_mysql_assoc ignores first recordphp_mysql_assoc 忽略第一条记录
【发布时间】:2011-02-09 23:51:18
【问题描述】:

您好,我正在尝试查询我的数据库以获取共享相同“ITEMID”的所有记录,该表是对数据库中的项目执行的操作的事务列表。

我检查了 phpmyadmin 中的 SQL 查询,它工作正常,但是当我运行 php 代码时,它每次都会忽略第一条记录。这是我的代码

<?php 
 // Get the quantity of each item 
 $sql1 = 'SELECT  `IDPENTERED` ,  `ITEMID` ,  `QTY` ,  `VALUE` FROM  `tblpieceentered` 
  WHERE  `ITEMID` =307 ' ;

 echo $sql1."<br>";

 // Retrieve all the data from the table
 $result1 = mysql_query($sql1)
 or die(mysql_error()); 

 // store the record of the table into $row1
 $row1 = mysql_fetch_array( $result1 ); 

 $i = 1; 
 $num = mysql_num_rows ($result1);

 echo "Num rows: $num <br>"; 

 while ($row1 = mysql_fetch_assoc ( $result1)) {
    $data_array[$i] = $row1;
$i++;
 }

echo "<pre>";
print_r ($data_array);
echo "</pre>";
?>

结果是:

SELECT `IDPENTERED` , `ITEMID` , `QTY` , `VALUE` FROM `tblpieceentered` WHERE `ITEMID`     =307 
Num rows: 5 

Array
(
    [1] => Array
        (
            [IDPENTERED] => 1999
            [ITEMID] => 307
            [QTY] => -1
            [VALUE] => -0.21
        )

    [2] => Array
        (
            [IDPENTERED] => 2507
            [ITEMID] => 307
            [QTY] => -10
            [VALUE] => -2.1
        )

    [3] => Array
        (
            [IDPENTERED] => 3039
            [ITEMID] => 307
            [QTY] => 1
            [VALUE] => 0.21
        )

[4] => Array
        (
            [IDPENTERED] => 3040
            [ITEMID] => 307
            [QTY] => -1
            [VALUE] => -0.21
        )

) 

有什么想法吗?

谢谢 肖恩

【问题讨论】:

  • 我的回答之外的主题补充:除非您希望您的数组从 '1' 开始,否则您可以使用 $data_array[] = $row 并跳过 $i 计数器。它将每一行追加到数组的末尾。

标签: php mysql


【解决方案1】:

mysql_fetch_array 已经获取了第一行。您不会在数组中添加这一行。 while 循环从第二行继续。

【讨论】:

    【解决方案2】:

    使用 mysqli 和 fetch_all 会更有效率:

    mysql_fetch_array add all rows?

    【讨论】:

    • 谢谢@f00 今天晚些时候我会试一试,因为查询返回超过 1500 条记录,并且数据库一直在增长。
    【解决方案3】:

    那是因为您在 while 循环之前获取第一项。

    删除$row1 = mysql_fetch_array( $result1 ); 行,你应该会很好。

    或者,如果您希望在循环之前访问第一行,则可以使用 do-while 循环:

    // store the record of the table into $row1
    $row1 = mysql_fetch_array( $result1 ); 
    $i = 1; 
    $num = mysql_num_rows ($result1);
    echo "Num rows: $num <br>";
    do {
       $data_array[$i] = $row1;
       $i++;
    } while ($row1 = mysql_fetch_assoc ( $result1));
    

    【讨论】:

      【解决方案4】:

      这是你的第一张唱片:

      $row1 = mysql_fetch_array( $result1 ); 
      

      循环从下一个(第二个)记录开始:

      while ($row1 = mysql_fetch_assoc ( $result1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-23
        • 2018-02-04
        • 2011-09-22
        • 1970-01-01
        • 2014-05-07
        相关资源
        最近更新 更多