PHP MySQL Select
- Previous Page MySQL Insert
- Next Page MySQL Where
The SELECT statement is used to select data from a database.
Selecting data from a database table
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s) FROM table_name
Note:SQL statements are case-insensitive. SELECT is equivalent to select.
To make PHP execute the above 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 (* character selects all data in the table):
<?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 example above 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 in the record set as an array. Each subsequent call to mysql_fetch_array() returns the next row in the record set. The while loop statement will iterate through all the records in the record set. To output the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).
The output of the above code is:
Peter Griffin Glenn Quagmire
Displaying Results in an HTML Table
The following example selects the same data as the above example, but displays the data in an HTML table:
<?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 is:
Firstname | Lastname |
---|---|
Glenn | Quagmire |
Peter | Griffin |
- Previous Page MySQL Insert
- Next Page MySQL Where