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:

CodenamesCodenamesCodenames is a social word game with a simple premise and challenging game play. Two rival spymasters know the secret identities of 25 agents. Their t... Read More >
MySQL Troubleshooting: What To Do When Queries Don't WorkMySQL Troubleshooting: What To Do When Queries Don't Work

Stuck with bugs, performance problems, crashes, data corruption, and puzzling output? If you’re a database programmer or DBA, they’re part of y... Read More >

Code Blue: A  Political Suspense Novel (Romance, Action, Thriller, Mystery)Code Blue: A Political Suspense Novel (Romance, Action, Thriller, Mystery)Could Israel become a theocratic military dictatorship? A novel that could be tomorrow's news.They really had nothing in common. Rinat was divorcée, ... Read More >
Related Posts Plugin for WordPress, Blogger...