PHP is a widely used server-side scripting language that can be used in conjunction with the MySQL database to achieve various data operations. This article will introduce how to use PHP to query a piece of data in the MySQL database.
First of all, you need to ensure that the MySQL database has been established and the database contains the data tables that need to be queried. For example, you can use the following SQL statement to create a data table named "users":
CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, email VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL )
The above SQL statement creates a data table containing four fields, where id is an auto-incrementing primary key, name, email and Password represents username, email and password respectively.
Assume that you need to query a user named "John", you can write the following PHP code:
<?php // 连接到MySQL数据库 $servername = "localhost"; $username = "root"; $password = "123456"; $dbname = "mydatabase"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 执行查询语句 $name = "John"; $sql = "SELECT * FROM users WHERE name='$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 "0 结果"; } // 关闭数据库连接 $conn->close(); ?>
The above code first connects to the MySQL database, and then executes the SELECT statement to query the user named "John" user and store the query results in the $result variable. If the query is successful, use a while loop to traverse the query results and output the query results to the page. If the query result is empty, "0 results" are output.
Using the above method, you can easily query a piece of data in the MySQL database. It is worth noting that in order to avoid SQL injection attacks, the input values should be filtered and escaped before submitting to the database to ensure the security of the query.
The above is the detailed content of How to query a data of mysql in php. For more information, please follow other related articles on the PHP Chinese website!