如何遍历数据库中的每个项目

时间:2019-02-19 14:55:18

标签: php sql database loops

我正在编写一个PHP脚本,我必须在该脚本中从数据库获取数据并将结果转换为静态HTML页面。我试图遍历特定数据库中的所有项目,并一一遍历,并在进行过程中获取其“ nid”列中的值。我启动了脚本。我有数据库连接。只是停留在我应该如何做循环。应该是while循环还是for循环?如果是这样,我该如何依次遍历表1中的项目并获取特定的列值?还附带了数据库的屏幕快照,因此您可以看到我要定位的列。 enter image description here

<?php
    // Establish all database credential variables
    $serverName = "localhost";
    $username = "admin";
    $password = "peaches";
    $databaseName = "static_site";

    // Create Database Connection
    $connection = new mysqli($serverName, $username, $password, $databaseName);

    // Check Database Connection
    if ($connection->connect_error) {
      die("Connection failed:" . $connection->connect_error);
    } // line ends if statement

    $queryNodeRevision = "SELECT nid FROM node_revision";
    // line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"

    $dataBaseQueryResults = mysqli_query($connection, $queryNodeRevision);
    // line above creates variable $dataBaseQueryResults > actually queries the database and passes in 2 variables
    // passes in database connection variable and variable that selects "nid" column from "node_revision" table
    ?>

1 个答案:

答案 0 :(得分:0)

使用while loopmysqli_fetch_array为每一行获取nid的值。

$queryNodeRevision = "SELECT nid FROM node_revision";

$results=mysqli_query($queryNodeRevision);

while ($row = mysqli_fetch_array($results)) {

    echo $row['nid'];
}