I have this table for example
+------+---------+------+
| id | item_id | type |
+------+---------+------+
| 1 | 2 | book |
| 1 | 1 | pen |
+------+---------+------+
I want retrieve all the data where id=1 in a php script, here is the code i used
<?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);
?>
the result is: 开发者_开发知识库Array ( [item_id] => 2 [type] => book )
and that is only the first row, how to retrieve all the rows in the php code?
Use this
<?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);
}
?>
by the way: i would call the $stat
variable $query
(as it is your query). The $query
variable actually contains a result, so I would call that $result
and your fetch array might be called something else too..
You have a function called mysql_fetch_array to read about at http://php.net/manual/en/function.mysql-fetch-array.php
Try this example:
<?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);
?>
For more http://www.w3schools.com/php/php_mysql_select.asp
Well. For oneyou can do that:
<?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 );
}
?>
精彩评论