从DB中抓取不止一行

时间:2014-11-17 15:39:26

标签: php mysql mysqli

$sql = "SELECT title, article, filename, caption FROM articles 
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();

var_dump($row);

这只抓取数据库中的第一行,当我需要它来抓取所有行时。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

fetch_assoc()会在每次调用时返回结果集的下一行,因此您需要在这样的循环中调用它:

while($row = $result->fetch_assoc()) {
    var_dump($row);
}

循环在$row = null结束时(即结果集中不再有行)。

答案 1 :(得分:0)

请查看Quick start guide,更具体地说是Executing statements章节。就在那个页面上:

$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();

echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    echo " id = " . $row['id'] . "\n";
}