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:

How to Code in 10 Easy Lessons: Learn how to design and code your very own computer game (Super Skills)How to Code in 10 Easy Lessons: Learn how to design and code your very own computer game (Super Skills)

Learn how to code in 10 easy lessons, and become a computer pro in no time!

From writing simple coding instructions using Scratch software, t... Read More >

PHP and MySQL Web Development (4th Edition)PHP and MySQL Web Development (4th Edition)PHP and MySQL Web Development, Fourth Edition
The definitive guide to building database-drive Web applications with PHP and MySQL

PHP ... Read More >
PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)It hasn't taken Web developers long to discover that when it comes to creating dynamic, database-driven Web sites, MySQL and PHP provide a winning ope... Read More >
Related Posts Plugin for WordPress, Blogger...