【问题标题】:retrieving many rows php-mysql检索许多行 php-mysql
【发布时间】:2011-04-15 07:39:42
【问题描述】:

例如我有这张表

+------+---------+------+
| id   | item_id | type |
+------+---------+------+
|    1 |       2 | book |
|    1 |       1 | pen  |
+------+---------+------+

我想在 php 脚本中检索 id=1 的所有数据,这是我使用的代码

 <?php 
    $stat="select item_id, type from tb where id=1"; 
    $query = mysqli_query($con, $stat); 
    $result = mysqli_fetch_array($query,MYSQLI_ASSOC);
    print_r($result); 
  ?>

结果是:Array ( [item_id] =&gt; 2 [type] =&gt; book ) 而且这只是第一行,如何检索php代码中的所有行?

【问题讨论】:

标签: php mysql


【解决方案1】:

使用这个

 <?php 
    $stat="select item_id, type from tb where id=1"; 
    $query = mysqli_query($con, $stat); 
    while($result = mysqli_fetch_array($query,MYSQLI_ASSOC)){
        print_r($result); 
    }
  ?>

顺便说一句:我会调用$stat 变量$query(因为这是您的查询)。 $query 变量实际上包含一个结果,所以我将其称为 $result 并且您的 fetch 数组也可能被称为其他名称..

【讨论】:

    【解决方案2】:

    你有一个名为 mysql_fetch_array 的函数可以在http://php.net/manual/en/function.mysql-fetch-array.php阅读

    试试这个例子:

    <?php
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("my_db", $con);
    
    $result = mysql_query("SELECT * FROM Persons");
    
    while($row = mysql_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName'];
      echo "<br />";
      }
    
    mysql_close($con);
    ?>
    

    了解更多http://www.w3schools.com/php/php_mysql_select.asp

    【讨论】:

      【解决方案3】:

      嗯。你可以这样做:

      <?php
          $stat = "SELECT `item_id`, `type` FROM `tb` WHERE `id` = 1"; 
          $query = mysqli_query( $con, $stat );
      
          while ( null !== ( $result = mysqli_fetch_assoc( $query ) ) )
          {
              print_r( $result );
          } 
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 2014-03-19
        • 2011-07-19
        • 2013-01-02
        相关资源
        最近更新 更多