Making a simple query to a MySQL database via PHP


2012-01-26

To make a query to a MySQL database using PHP, you will first create the PHP script. I'm assuming that you have created your database and have the connection information.

/*declare your connection information*/
$host = 'yourHost';
$databaseUser = 'yourUser';
$databasePassword = 'yourPassword';
$databaseName = 'yourDatabase';

/*Connect to the host and select the database*/
mysql_connect($host,$databaseUser,$databasePassword);
@mysql_select_db($databaseName) or die( "Unable to select database");

/*create a query. here we will select all entries from the posts table*/
$query = "SELECT * FROM `posts`";

/*execute the query and assign the result to a variable*/
$result =  mysql_query($query);

/*grab the number of rows returned by the query*/
$rowCount=mysql_numrows($result);

/*close the connection*/
mysql_close();

/*the following while loop goes through all the rows of the result 
and outputs the 'title' of each entry of the posts table*/

echo "<html>";
$i=0;
while ($i < $rowCount) {

    $title=mysql_result($result, $i, "title");

    echo "$title <br>";

    $i++;
}
echo "</html>";

Then you can take this script and create a webpage where the title to each entry will be outputted in HTML.