Home > Database > Mysql Tutorial > body text

How to query data in php mysql

藏色散人
Release: 2020-07-25 09:23:09
Original
3188 people have browsed it

How to query data with php mysql: first create a php mysql connection; then set up an SQL statement to read field information from the data table; then use the SQL statement to retrieve the result set from the database and assign it to the variable " $result"; finally return the data information.

How to query data in php mysql

Recommended: "mysql tutorial"

PHP MySQL reading data

Using MySQLi

In the following example, we read the data of the id, firstname and lastname columns from the MyGuests table of the myDB database and display it on the page:

Example (MySQLi - Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
 
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
} 
 
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    // 输出数据
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 结果";
}
$conn->close();
?>
Copy after login

The above code is analyzed as follows:

First, we set up the SQL statement to read the three fields id, firstname and lastname from the MyGuests data table. We then use this SQL statement to retrieve the result set from the database and assign it to the copied variable $result.

Function num_rows() determines the returned data.

If multiple pieces of data are returned, the function fetch_assoc() will put the combined set into an associative array and output it in a loop. while() loops out the result set and outputs the three field values ​​id, firstname and lastname.

The above is the detailed content of How to query data in php mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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!