PHP + MySQL tutorial (5): The MySQLSelect SELECT statement is 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 not case sensitive. 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 "Person" table (* selects all data in the table ):
$ 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 person ");
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
Display the result in the HTML table.
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:
$ 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 person ");
Echo"
While ($ row = mysql_fetch_array ($ result ))
{
Echo"
Firstname |
Lastname |
";
";Echo"
". $ Row ['firstname']." | ";Echo"
". $ Row ['lastname']." | ";Echo"
";}Echo"
";
Mysql_close ($ con );
?> Output of the above code:
Firstname Lastname
Glenn Quagmire
Peter Griffin