How to display database tables in PHP?

To display a database table in PHP, you can follow these steps:

  1. establish a connection using mysqli
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";

// 使用mysqli连接到数据库
$conn = mysqli_connect($servername, $username, $password, $dbname);

// 使用PDO连接到数据库
$dsn = "mysql:host=$servername;dbname=$dbname";
$pdo = new PDO($dsn, $username, $password);
  1. execute a query using MySQLi
  2. To ask a question or make an inquiry.
// 使用mysqli查询数据库表
$query = "SELECT * FROM tablename";
$result = mysqli_query($conn, $query);

// 使用PDO查询数据库表
$query = "SELECT * FROM tablename";
$result = $pdo->query($query);
  1. Retrieves an associative array of the fetched row using MySQLi.
  2. perform a data retrieval operation using the fetch() method
// 使用mysqli处理查询结果
while ($row = mysqli_fetch_assoc($result)) {
    echo "Name: " . $row["name"] . "<br>";
    echo "Email: " . $row["email"] . "<br>";
}

// 使用PDO处理查询结果
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "Name: " . $row["name"] . "<br>";
    echo "Email: " . $row["email"] . "<br>";
}
  1. Closing the MySQL database connection using mysqli_close().
  2. There is no response available in English.
// 使用mysqli关闭数据库连接
mysqli_close($conn);

// 使用PDO关闭数据库连接
$pdo = null;

The above is a simple example used to display data from a database table. Depending on the actual needs, it may be necessary to perform operations such as pagination and sorting on the query results.

bannerAds