Home >Backend Development >PHP Problem >php database query display
As a programming language widely used in Web development, PHP basically cannot avoid database query and display operations. This article will briefly introduce how to use PHP to query the database and present the query results to the user in a beautiful way.
1. Connect to the database
Before using PHP to query the database, you need to connect to the database first. The following is a code example for connecting to a MySQL database:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "databaseName"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } ?>
2. Database query
PHP provides a variety of methods for database query. Here are two commonly used methods: mysqli and PDO.
<?php $sql = "SELECT id, name, age FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "0 结果"; } $conn->close(); ?>
<?php $sql = "SELECT id, name, age FROM users"; $stmt = $pdo->prepare($sql); $stmt->execute(); if ($stmt->rowCount() > 0) { // 输出每行数据 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "0 结果"; } ?>
3. Data display
After querying the data, we need to display the data to the user. Here we use HTML and CSS to beautify the display effect.
<ul> <?php while($row = $result->fetch_assoc()) { echo "<li>". $row["name"]. " - ". $row["age"]. "</li>"; } ?> </ul>
<table> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <?php while($row = $result->fetch_assoc()): ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['age']; ?></td> </tr> <?php endwhile; ?> </table>
4. Security Precautions
When performing database query and display operations, you need to pay attention to several security issues:
Summary
This article briefly introduces the operation of database query and display in PHP, and provides sample code and further security considerations. I hope readers can develop safer, more beautiful, and more practical Web applications based on this knowledge.
The above is the detailed content of php database query display. For more information, please follow other related articles on the PHP Chinese website!