PHP: Accessing Databases

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Accessing Databases

Aims: to learn how to write a PHP script that

PHP and databases

A small example

Assume the Sudury Bird Sanctuary database has been created and populated with data
<?php 
 // Try to connect to database
 $dbconnection = mysql_connect($host, $user, $password);
 if ( ! $dbconnection )
 {
    die('Unable to connect!');
 }
 
 // Try to select database
 $dbselection = mysql_select_db($dbname);
 if ( ! $dbselection )
 {
    die('Unable to select database');
 }
 
 // Query the database
 $sql = "SELECT * FROM birds;";
 $dbresult = mysql_query($sql);
 if ( ! $dbresult )
 {
    die('Error in query ' . mysql_error());
 }
 // Display the results of the query
 if (mysql_num_rows($dbresult) == 0) 
 {
    echo 'No rows found';
 }
 else 
 {
    // Output each row of query results
    while ($row = mysql_fetch_assoc($dbresult)) 
    {
       echo "<p>$row[num] $row[name] $row[species]</p>";
    }
 }
 
 // Free up memory and close the connection
 mysql_free_result($dbresult);
 mysql_close($dbconnection);
?>

Connecting to the database server

Checking that the connection is made

Checking that the connection is made

Selecting a database

Creating a query and executing it

Processing the result set

Processing the result set, continued

Processing the result set, continued

Freeing the space and closing the connection

Inserting values

Imagine that $snum, $bnum and $donation contain values, e.g. from a form, and that we have validated them
<?php
 // Try to connect to database
 $dbconnection = mysql_connect($host, $user, $password);
 if ( ! $dbconnection )
 {
    die('Unable to connect!');
 }
 
 // Try to select database
 $dbselection = mysql_select_db($dbname);
 if ( ! $dbselection )
 {
    die('Unable to select database');
 }
 
 // Insert into the database
 $sql = "INSERT INTO donations (snum, bnum, donation)
         VALUES ({$snum}, {$bnum}, {$donation});";
 $dbresult = mysql_query($sql);
 if ( ! $dbresult )
 {
    die('Error in query ' . mysql_error());
 }
 
 // Close the connection
 mysql_close($dbconnection);
?>

Notes on insertion