How can PHP retrieve database content?
In PHP, you can read database content using the following steps:
- Connect to the database: use extension libraries such as MySQLi or PDO to establish a connection with the database. For example, use the MySQLi extension library to connect to a MySQL database.
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
- Execute an SQL query: Use SQL statements to perform a query in the database. For example, select all rows from a table named “users”.
$sql = "SELECT * FROM users";
$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 "0 结果";
}
- Close the database connection: After completing database operations, close the database connection to release resources.
$conn->close();
The code above selects all rows from the “users” table and outputs the ID, name, and email for each row.
Please note that the above examples use the MySQLi extension library. If you are using the PDO extension library, the code may be different, but the basic concept is the same.