phpSlash.org

Accessing a MySQL database using PHP

The following is an example of how to connect to a MySQL database using PHP. In the example, we are connecting to a database using the username "jsmith" and the password "1234". A successful connection will store a link identifier in the variable $link, otherwise an error will be displayed.

$host = "hostname";
$user = "jsmith";
$pwd = "1234";

$link = mysql_connect($host,$user,$pwd);
if (!$link) {
  echo("ERROR: " . mysql_error() . "\n");
}

Now for an example of how to execute an SQL statement using PHP. In this example, we will be retreiving a price and stock count using a product id number.

$SQL = "SELECT price, stock FROM products WHERE id=101";
if ($link) $query_result =
mysql_db_query("database name", $SQL, $link);

if (!$query_result) {
  echo("ERROR: " . mysql_error() . "\n");
}

while ($row = mysql_fetch_array($query_result)) {
  echo $row["price"];
  echo $row["stock"];
}

<-- Previous