How to display database tables in PHP?
To display a database table in PHP, you can follow these steps:
- 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);
- execute a query using MySQLi
- 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);
- Retrieves an associative array of the fetched row using MySQLi.
- 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>";
}
- Closing the MySQL database connection using mysqli_close().
- 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.