检索许多行php-mysql

时间:2011-04-15 07:39:42

标签: php mysql

我有这个表例如

+------+---------+------+
| 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] => 2 [type] => book ) 那只是第一行,如何检索php代码中的所有行?

3 个答案:

答案 0 :(得分:5)

使用此

 <?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数组也可能会被调用。

答案 1 :(得分:1)

你有一个名为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

答案 2 :(得分:1)

好。你可以做到这一点:

<?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 );
    } 
?>
相关问题