Home >Database >Mysql Tutorial >How to query a data of mysql in php

How to query a data of mysql in php

WBOY
WBOYforward
2023-05-29 11:25:491599browse

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
)

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();
?>

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete