How to Connect to a MySQL Database using PHP

March 29, 2005 by  
Filed under Code Snippets, PHP, Scripts and Coding

I was helping my coworker yesterday to create her first PHP-Database program. She already knew how phpMyAdmin worked, so I created a sample page for her to show how to connect to the database and then retrieve data from a query. Maybe this sample page could help you too. I commented as much of the code as I could. Let me know if you have any questions.

<?php

/* 
	Purpose: This file demonstrates how to run 
		and display a mySQL query using PHP. 
	Author : Daynah
	Created: 2005/03/28
*/

// Variables for database
$username     = "TestUser";
$dbpword      = "TestPassword";
$database     = "test_database_name";
$host         = "localhost";

// Connect to the database
$db = mysql_connect($host, $username, $dbpword ) 
	or die ("ERROR: " .mysql_error());
$connection = mysql_select_db( $database, $db );

// Run a query
$query = "SELECT * FROM myTestTable";		// The mysql statement
$result = mysql_query($query);				// The results of a query
$num_rows = mysql_num_rows($result);		// Number of rows of data

// Start the table to display the data
echo '<table>';

// If there is data in that query, display the data
if($num_rows)
{
	// PHP Script to iterate through the data in the database
	// This will print out each Table Row
	/*	|   ID	| Name	|  Address	|
		-----------------------------
			1	  Name1		Address1
			2	  Name2		Address2
		Assuming there are three fields in the table -- ID, Name, and Address
	*/
	while($myData = mysql_fetch_object($result)
	{
		// Print Each Row of Data -- ID, Name, Address
		echo '<tr><td>'. $myData->ID.'</td>
				  <td>'. $myData->Name.'</td>
				  <td>'. $myData->Address.'</td>
			  </tr>';
	}
}

// If there is no data in the database.
else
{
	echo '<tr><td>Sorry, there is no data in the database.</td></tr>';
}

// Close the table tag
echo '</table>';

// Close Mysql Connection
mysql_close();

?>

Related Products:

Related Posts Plugin for WordPress, Blogger...