PHP Select Data From MySQL
Read data from MySQL database
The SELECT statement is used to read data from the data table:
SELECT column_name ( s ) FROM table_name
We can use * to read all fields in the data table:
SELECT * FROM table_name
In the following example, we read the id, firstname and lastname columns from the MyGuests table of the myDB database and display them on the page:
Instance (MySQLi-Object Oriented)
The above code is parsed as follows:
First, we set up an SQL statement to read the id, firstname and lastname fields from the MyGuests data table. We then use this SQL statement to fetch the result set from the database and assign it to the variable $ result.
The function num_rows () determines the data returned.
If multiple pieces of data are returned, the function fetch_assoc () puts the join set into the associative array and loops the output. while () loops out the result set and outputs three field values of id, firstname and lastname.
The following example uses MySQLi's process-oriented approach, and the effect is similar to the above code:
Example (MySQLi-process oriented)
Using PDO (+ preprocessing)
The following example uses prepared statements.
The id, firstname and lastname fields in the MyGuests table are selected and placed in the HTML table: