The SELECT statement is used to select data from the database.
Select data from a database table
The SELECT statement is used to select data from the database.
Grammar
SELECT column_name (s) from table_name
Note: SQL statements are insensitive to case. The select is equivalent to select.
In order for PHP to execute the above statement, we must use the mysql_query () function. This function is used to send a query or command to MySQL.
Example
The following example selects all data stored in the "Persons" table (all data in the * character pick table):
code is as follows |
copy code |
<?php $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 "<br/>"; } Mysql_close ($con); |
The above example holds 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 recordset as an array. Each subsequent call to the Mysql_fetch_array () function will return the next row in the recordset. The while loop statement loops through all the records in the recordset. To output the value of each row, we used the $row variables of PHP ($row [' FirstName '] and $row [' LastName ']).
The output of the above code:
Peter Griffin
Glenn Quagmire
--------------------------------------------------------------------------------
Display results in an HTML table
The following example selects the same data as the example above, but displays the data in an HTML table:
The code is as follows |
Copy Code |
<?php $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 "<table border= ' 1 ' > <tr> <th>Firstname</th> <th>Lastname</th> </tr> "; while ($row = Mysql_fetch_array ($result)) { echo "<tr>"; echo "<td>". $row [' FirstName ']. "</td>"; echo "<td>". $row [' LastName ']. "</td>"; echo "</tr>"; } echo "</table>"; Mysql_close ($con); ?>
|
The output of the above code:
Firstname Lastname
Glenn Quagmire
Peter Griffin