SQL查询如何从多行返回数据

时间:2017-05-28 16:22:18

标签: php mysql database select

<?php
$con = mysqli_connect("localhost","root","","register");
$sql = "SELECT * FROM photos WHERE user_id ='$id'";
$result = mysqli_query($con,$sql);
$array = mysqli_fetch_assoc($result);
$rowcount = mysqli_num_rows($result);
$source  = $array['photo'];
?>

我想从colomn照片中获取数据,但如果我有多个具有相同user_id的行,$source = $array['photo']仅从第一行返回数据。 如何从具有相同user_id的所有行获取数据?

我的数据库是:

+----+---------+----------+
| id | user_id | photo    |
+----+---------+----------+
|  1 |    14   | 1010.jpg |
|  2 |    14   | 1013.jpg |
|  3 |    14   | 1210.jpg |
|  4 |    10   | 1173.jpg |
|  5 |    20   | 2038.jpg |
+----+---------+----------+

1 个答案:

答案 0 :(得分:1)

<?php
$con = mysqli_connect("localhost","root","","register");
$sql = "SELECT * FROM photos WHERE user_id ='$id'";
$result = mysqli_query($con,$sql);
$rowcount = mysqli_num_rows($result);

while ($row = mysqli_fetch_assoc($result)) {
  $source = $row['photo];
  // do stuff with $source
}
?>

查看有关mysqli_fetch_assoc的文档。