MySQL Select

SELECT, which is used to get information from the database, so that its data can be used in our PHP script.

Syntax:

SELECT * FROM table_name;

and

SELECT column_name(s) FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

In this example we will select everything in our table “employee” and put it into a nicely formatted HTML table. Assume the ‘employee’ table has three fields id, name and age.

Remember, if you don’t understand the HTML or PHP code, be sure to check out the HTML and/or PHP Tutorial.

PHP & MySQL Code:

<?php
// Make a MySQL Connection
mysql_connect("localhost", "dbusername", "dbpassword") or die(mysql_error());
mysql_select_db("test_db") or die(mysql_error());

// Get all the data from the "employee" table
$select_q = "SELECT * FROM employee";
$select_r = mysql_query($select_q);
?>
<table border="0" width="100%" align="center">
<tr><td>Id</td><td>Name</td><td>Age</td></tr>
<?php
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $select_r ))
{
// Print out the contents of each row into a table
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php
}
?>
</table>

mysql_query() – This function will execute SQL

Posted in MySQL