【问题标题】:mysql_fetch_array showing the first row only when using while loopmysql_fetch_array 仅在使用 while 循环时显示第一行
【发布时间】:2017-08-23 04:19:05
【问题描述】:

不久我在使用while循环时遇到了一个问题......我不知道发生了什么,所以,我认为我应该寻求帮助,经过大量搜索,我知道 mysql_fetch_array 每次都返回一个 row,所以如果我们需要从查询中获取所有行,我们应该使用 while。 在尝试避免 while 并使用 foreach 之后,我发现根本不能使用 foreach 代替 while或者我们可以在 while 之后将其用作另一个循环。 无论如何,我的问题是:我在 数据库中创建了一个存储过程,并且它工作正常,使用 抛出我的 代码,但是当我尝试根据某些数据的ID 将它放入循环时, while 循环 仅在计算后才给我第一行。 所以如果有人能看到我在代码中看不到的东西,请不要犹豫。 谢谢..

$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$thefinalres="";    
$loop = mysql_query("SELECT * FROM mrh_chains order by id");
        if ($loop){
            while ($row = mysql_fetch_array($loop))
            {
                $theid = $row['id'];
                $thename = $row['name'];
                //CALL PROCEDURE 
                $result = mysql_query("CALL calccommission($theid,'$startdate','$enddate')");
                if ($result){
                    $row2 = mysql_fetch_array($result);
                    if ($row2[0]!=""){
                        $thecommission = $row2[0];
                    } else {
                        $thecommission = "Try to change dates, There are no data on these dates";
                    }
                    $thefinalres .= $thename . " commission: ". $thecommission . "<br/>";
                }
            }

            $value =  array('msg' => 'true' );
            $value["res"] = $thefinalres;

        } else {
            $value =  array('msg' => 'false' );
        }

【问题讨论】:

  • 那么您确定SELECT * FROM mrh_chains order by id 返回多行吗?你确定问题是迭代而不是条件逻辑吗?添加一些调试行?
  • 是的,当然,即使我在 php 文件中单独尝试了 while 循环,它也能正常工作,并且得到所有行,但在此过程之后,它只给我第一行
  • 您检查日志文件是否有错误?
  • 已检查,完全没有错误
  • 您没有检查错误。在循环中进行查询并不是一个好方法。

标签: mysql php ajax php


【解决方案1】:

经过 looooooooooooooooooot 的搜索,我找到了 的解决方案

$mysqli = new mysqli(  "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );
if( $res ) {
  $results = 0;
  do {
    if ($result = $mysqli->store_result()) {
      printf( "<b>Result #%u</b>:<br/>", ++$results );
      while( $row = $result->fetch_row() ) {
        foreach( $row as $cell ) echo $cell, "&nbsp;";
      }
      $result->close();
      if( $mysqli->more_results() ) echo "<br/>";
    }
  } while( $mysqli->next_result() );
}
$mysqli->close();

我在这篇文章中找到了答案:https://forums.mysql.com/read.php?52,198596,198717

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 2012-10-30
    • 2012-08-30
    • 2019-09-27
    • 2013-10-07
    • 2012-08-18
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多