The PHPMySQL Getting Started Tutorial reads data from a database. For more information about how to read data from a database in a simple PHPMySQL Getting Started Tutorial, see. SELECT statements are used to SELECT data from the database. Select data SEL from the database table a super simple PHP MySQL getting started tutorial to read data from the database instance, you can refer.
SELECT statements are used to SELECT data from the database.
Select data from the database table
SELECT statements are used to SELECT data from the database.
Syntax
SELECT column_name (s) FROM table_name
Note: SQL statements are case-insensitive. SELECT is equivalent to select.
To allow PHP to execute the preceding statement, we must use the mysql_query () function. This function is used to send queries or commands to MySQL.
Example
The following example selects all data stored in the "Persons" table (* All data in the character selection table ):
The code is as follows: |
|
$ Con = mysql_connect ("localhost", "peter", "abc123 "); If (! $ Con) { Die ('could not connect: '. mysql_error ()); } Mysql_select_db ("my_db", $ con ); $ Result = mysql_query ("SELECT * FROM Persons "); While ($ row = mysql_fetch_array ($ result )) { Echo $ row ['firstname']. "". $ row ['lastname']; Echo" "; } Mysql_close ($ con ); ?>
|
The preceding example stores the data returned by the mysql_query () function in the $ result variable. Next, we use the mysql_fetch_array () function to return the first row from the record set in the form of an array. Each subsequent call to the mysql_fetch_array () function returns the next row in the record set. The while loop statement cyclically records all records in the record set. To output the values of each row, we use the $ row variable ($ row ['firstname'] and $ row ['lastname']) of PHP.
Output of the above code:
Peter Griffin
Glenn Quagmire
--------------------------------------------------------------------------------
Display results in HTML tables
The data selected in the following example is the same as that in the preceding example, but the data is displayed in an HTML table:
The code is as follows: |
|
$ Con = mysql_connect ("localhost", "peter", "abc123 "); If (! $ Con) { Die ('could not connect: '. mysql_error ()); } Mysql_select_db ("my_db", $ con ); $ Result = mysql_query ("SELECT * FROM Persons "); Echo"
Firstname |
Lastname |
";While ($ row = mysql_fetch_array ($ result )){Echo"
";Echo"
". $ Row ['firstname']." | ";Echo"
". $ Row ['lastname']." | ";Echo"
";}Echo"
"; Mysql_close ($ con ); ?>
|
Output of the above code:
Firstname Lastname
Glenn Quagmire
Peter Griffin
For more information about how to read data from a database, see getting started with MySQL. SELECT statements are used to SELECT data from the database. Select data SEL from the database table...