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