Charlie Calvert on Elvenware

Writing Code and Prose on Computers

Elvenware

PHP Database Basics

Index

PHP and Databases

PHP provides excellent support for working with MySql databases. The following commands play a key role:

The following script shows an example of how to access a database. Notice that after each call I report whether it succeeded or failed. In a production application, you don't want to provide so much feedback, as it will clutter the user's screen. But while you are learning, and while you are developing an application, this kind of feedback can be very useful and can save you a tremendous amount of time.

<html>
<body>
<?php
  print "<h1>A PHP Script that Connects to a MySQL Database</h1>";

  $con = mysql_connect("localhost", "someDatabase", "somePassword");
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }
  else
  {
    Print "<p>Connection is valid</p>";
  }

  $db_selected = mysql_select_db("someDatabase", $con);
  if (!$db_selected) 
  {
    die ('Can\'t use database : ' . mysql_error());
  }
  else
  {
    Print "<p>Using database charlie</p>";
  }

  $result = mysql_query("select first, last from presidents");

  // Check result
  // This shows the actual query sent to MySQL, and the error. Useful for debugging.
  if (!$result) 
  {
    $message = 'Invalid query: ' . mysql_error() . "\n"; 
    die($message);
  }
  else
  {
    Print "<p>selected rows from database</p>";
  }

  while($row = mysql_fetch_array($result))
  {
    print "<p>row found: " . $row['first'] . " " . $row['last'] . "</p>";
  }

  mysql_close($con);
?>
</body>
</html>

More Information

This same subject is also covered from the point of view of a database developer in one of the MySql pages:

http://www.elvenware.com/charlie/development/database/mysql/MySql.html