Archive for February, 2010

Connecting to MySQL with PHP

Tuesday, February 23rd, 2010

I recently put on a presentation for the MKEPUG meet-up group on the subject of connecting to a MySQL DB using PHP. Here it is:

Presentation

The Code

<?php
// Database Variables
$dbhost = 'localhost';
$dbname = 'demo';
$dbuser = 'public';
$dbpass = '1234';

// Connect to DB
$conn_id = mysql_connect($dbhost, $dbuser, $dbpass);

// Select the DB
mysql_select_db($dbname, $conn_id) or die(“Could not connect to DB”);

// Select the data from a table
$query = ”SELECT * FROM customers”;
$result = mysql_query($query, $conn_id);
?>
<html>
<head>
<title>MySQL Demo</title>
</head>
<body>
<h1>Customer Listing</h1>
<ul>
<?php
// Loop through results
while($row = mysql_fetch_array($result))
{
echo ”<li><strong>”.$row['name'].”</strong><br />”;
echo $row['street'].”<br />”;
echo $row['city'].” ”.$row['state'].” ”.$row['zip'].”</li>”;
}
?>
</ul>
</body>
</html>