Display MySQL Data Using PHP
You can use either the MySQLi extension or the PDO extension in PHP to connect to a MySQL database and retrieve data using the appropriate functions.
Here is an example code using the MySQLi extension:
// 创建数据库连接
$conn = new mysqli("localhost", "username", "password", "database_name");
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询数据库中的数据
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// 判断查询结果是否为空
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "没有数据";
}
// 关闭数据库连接
$conn->close();
Below is an example code using the PDO extension.
// 创建数据库连接
$dsn = "mysql:host=localhost;dbname=database_name";
$user = "username";
$pass = "password";
try {
$conn = new PDO($dsn, $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 查询数据库中的数据
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// 输出数据
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
// 关闭数据库连接
$conn = null;
In the above example code, localhost represents the MySQL database server address, username and password are the login credentials for accessing the database, database_name is the name of the database, and table_name is the table to be queried. Modify this information according to your actual situation.