How to Use Databases with PHP (Example)

Here is a simple example of how to use your MySQL database with a PHP script. The database used here is the one described in the Knowledge Base article How To Create a MySQL Database, in which we then created a table called books with 3 fields: ID, author, title. The following script will output the title and author of each book:

$dbh=mysql_connect ("localhost", "johndoe_mysqlusername", "") or die ('Connexion error: ' . mysql_error());
mysql_select_db ("johndoe_project01");

$sql = "SELECT * FROM books";
$result = mysql_query($sql) or die('SQL Error: ' . mysql_error());
while ($row = mysql_fetch_array($result)){
echo 'Title: ' . $row['title'] . ', ';
echo 'Author: ' . $row['author'] . '


For additional information, please refer to the PHP and MySQL web sites. A Google search of a specific problems also often turns up useful results!


Article ID: #HC5020

Was this answer helpful? Yes No