PHP is a powerful server-side scripting language that is widely used in web development. In web development, we often need to interact with the database and execute query statements to obtain data. This article will introduce you to how to write query statements and usage examples in PHP.
Before using PHP to query the database, you first need to establish a connection with the database. Generally, we will use the MySQL database as an example. The code to connect to the database is as follows:
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
Next, we can use PHP to execute the query statement to obtain data. The following is a simple query statement example to query all data in the 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 结果"; }
In order to prevent SQL injection attacks, we should use parameters query. The following is an example of using parameterized query:
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?"); $stmt->bind_param("i", $id); $id = 1; $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 结果"; } $stmt->close();
After completing the database query, we should close the connection with the database and release resources. The code to close the connection is as follows:
$conn->close();
Through the above examples, you can understand how to write query statements in PHP and learn how to use parameterized queries to improve data security. I wish you greater success in web development!
The above is the detailed content of PHP query statement usage example. For more information, please follow other related articles on the PHP Chinese website!