PHP MySQL reads data
Reading data from MySQL database
We have learned to add data to the database. In this section, we will talk about how to read the data from the database and display it on the page?
To query data, use select
## Category | Detailed explanation |
select | *from table; |
select * from MyGuests; | |
Query MyGuests All results in all fields in the table |
: "*" is a regular expression The expression is written to match all
If you want to learn more about SQL, please visit our SQL tutorial.
Instanceus Query the data we added to the MyGuests table and display it on the page
connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT * 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"] ." ".$row['email'] ."
"; } } else { echo "0 个结果"; } $conn->close(); ?>
The program running results:
See if it is our MyGuests table The data inside
But if we only want to query two of the fields, such as firstname and email, look at the example belowconnect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT firstname,email FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo " - Name: ". $row["firstname"]. "--------".$row['email'] ."
"; } } else { echo "0 个结果"; } $conn->close(); ?>
We only need to
*Just change it to a specific field:
Program running result: