Standard PHP Connect to MySQL

April 10th, 2009 | Categories: Programming | Tags: , ,

Here is a simple example of how to connect to a MySQL server using PHP and pull down some data inside the database.

<?php

// Connect to database server
$hd = mysql_connect(“myhost”, “username”, “password”)
or die (“Unable to connect.”);

// Select database
mysql_select_db (“database”, $hd)
or die (“Unable to select database.”);

// Execute sample query
$res = mysql_query(“SELECT * FROM customer”, $hd)
or die (“Unable to run query.”);

// Query number of rows in rowset
$nrows = mysql_num_rows($res);

// Output
echo “The query returned $nrows row(s):<br />”;

// Iteration loop, for each row in rowset
while ($row = mysql_fetch_assoc($res))
{
// Assigning variables from cell values
$data1 = $row["title"];
$data2 = $row["fname"];
$data3 = $row["lname"];
$data4 = $row["phone"];

// Outputting data to browser
echo “ROW# $nr : $data1 $data2 $data3 $data4 <br />”;
}

// Close the MySQL connection
mysql_close($hd);

?>

No comments yet.
TOP