How can we retrieve data from a database table using PH…
The steps for retrieving data from a database table using PHP are as follows:
- establish a connection to a MySQL database
- create a new instance of PDO()
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 使用mysqli连接数据库
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 使用PDO连接数据库
$dsn = "mysql:host=$servername;dbname=$dbname";
$conn = new PDO($dsn, $username, $password);
- Choose
$sql = "SELECT * FROM table_name";
- execute a query using MySQLi
- Execute the query using the connection.
// 使用mysqli执行查询
$result = mysqli_query($conn, $sql);
// 使用PDO执行查询
$result = $conn->query($sql);
- Retrieve an associative array of fetched data using MySQLi.
- Fetch the result.
// 使用mysqli处理结果
while ($row = mysqli_fetch_assoc($result)) {
// 处理每一行数据
echo $row['column_name'];
}
// 使用PDO处理结果
while ($row = $result->fetch()) {
// 处理每一行数据
echo $row['column_name'];
}
Before handling the results, ensure that you are connected to the database and the query statement has been executed successfully.