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:

Modern Database Management (10th Edition)Modern Database Management (10th Edition)Provide the latest information in database development.

Focusing on what leading database practitioners say are the most important aspects to ... Read More >
PHP Cookbook: Solutions and Examples for PHP ProgrammersPHP Cookbook: Solutions and Examples for PHP Programmers

When it comes to creating dynamic web sites, the open source PHP language is red-hot property: used on more than 20 million web sites today, PHP is... Read More >

Databases DeMYSTiFieD, 2nd EditionDatabases DeMYSTiFieD, 2nd Edition

 Learning DATABASE fundamentals just got a whole lot EASIER! Now you can design, build, and manage a fully functional database with ease. Thorough... Read More >

Related Posts Plugin for WordPress, Blogger...

Popularity: 25% [?]