Home > Database > Mysql Tutorial > body text

How to query a data of mysql in php

WBOY
Release: 2023-05-29 11:25:49
forward
1499 people have browsed it

Before querying, you must confirm that the MySQL database has been created and contains the data table to be queried. A data table named "users" can be created, for example, using the following SQL statement:

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
)
Copy after login

The above SQL statement creates a data table containing four fields, where id is an auto-incrementing primary key, name, email and password represent username, email and password respectively.

Suppose 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();
?>
Copy after login

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, you need to traverse the result set through a while loop and output the 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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!