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:

PHP Cookbook: Solutions & Examples for PHP ProgrammersPHP Cookbook: Solutions & Examples for PHP Programmers

Want to understand a certain PHP programming technique? Or learn how to accomplish a particular task? This cookbook is the first place to look. Wit... Read More >

The Code ThiefThe Code Thief(Revised Edition Jan '17: Edited by, New York Times Best Selling Editor: Robin Smith)
THE CODE THIEF is a fast paced, cyber, espionage thriller.<... Read More >
MySQL Cookbook: Solutions for Database Developers and AdministratorsMySQL Cookbook: Solutions for Database Developers and Administrators

MySQL’s popularity has brought a flood of questions about how to solve specific problems, and that’s where this cookbook is essential. When you... Read More >

Related Posts Plugin for WordPress, Blogger...