PHP is a popular server-side scripting language that can be used to write dynamic web applications. Querying name data is a very common task in web development. In this article, we will introduce how to use PHP to write code to query name data.
1. Preparation work
Before you start writing code, you need to do some preparation work, including:
These fields are used to store name data. In this article, the MySQL database will be used, but you can also use other databases such as MSSQL, Oracle, etc.
// 数据库连接参数 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功";
2. Write the code
After the above preparations, you can write the PHP code to query the name data.
The following is a PHP code sample for querying and displaying all name data:
// 查询所有名字数据 $sql = "SELECT id, first_name, last_name FROM name"; $result = $conn->query($sql); // 如果查询结果数量大于0,则显示每一条查询结果 if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_name"]. "<br>"; } } else { echo "0 结果"; }
This code query All data in the "name" table and display the results in a web browser.
The following is another PHP code sample for querying data based on name:
// 从表单中获取要查询的名字 $name = $_POST['name']; // 查询名字数据 $sql = "SELECT id, first_name, last_name FROM name WHERE first_name = '{$name}'"; $result = $conn->query($sql); // 如果查询结果数量大于0,则显示每一条查询结果 if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_name"]. "<br>"; } } else { echo "0 结果"; }
This code first starts with Get the name to be queried from the form, then query the data in the "name" table based on the name, and display the results in the web browser.
3. Summary
In this article, we introduce how to use PHP to write code to implement the function of querying name data. These codes can help developers easily query name data in Web applications. Of course, this is only a small part of it. In the actual development process, factors such as security and performance also need to be considered.
The above is the detailed content of How to query name data with PHP code. For more information, please follow other related articles on the PHP Chinese website!