PHP: Connecting to Databases

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Connecting to Databases

Aims: to learn how to write a PHP script that

PHP and databases

A small example

Assume the Nerdland Bird Sanctuary database has been created and populated with data

 
// Try to connect to database
$dbconnection = mysqli_connect( $host, $user, $password, $dbname );
if ( ! $dbconnection )
{
    die('Unable to connect to database');
}
 
// Query the database
$sql = "SELECT * FROM birds;";
$dbresult = mysqli_query( $dbconnection, $sql );
if ( ! $dbresult )
{
    die('Error in query ' . mysqli_error( $dbconnection ));
}

// Display the results of the query
if ( mysqli_num_rows( $dbresult ) == 0 ) 
{
    echo "<p>No rows found</p>";
}
else 
{
    // Output each row of query results
    while ( $row = mysqli_fetch_assoc( $dbresult ) ) 
    {
        echo "<p>{$row['bnum']} {$row['name']} {$row['species']}</p>";
    }
}
 
// Free up memory and close the database connection
mysqli_free_result( $dbresult );
mysqli_close( $dbconnection );

Connecting to the database server

Checking that the connection is made

Checking that the connection is made

Creating a query and executing it

Processing the result set

Processing the result set, continued

Unbounded repetition or bounded repetition

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

// Try to connect to database
$dbconnection = mysqli_connect( $host, $user, $password, $dbname );
if ( ! $dbconnection )
{
    die('Unable to connect to database');
}

// Insert into the database
$sql = "INSERT INTO donations (snum, bnum, donation)
        VALUES ({$snum}, {$bnum}, {$donation});";
$dbresult = mysqli_query( $dbconnection, $sql );
if ( ! $dbresult )
{
    die('Error in query ' . mysqli_error( $dbconnection ));
}
 
// Close the connection
mysqli_close( $dbconnection );

Notes on insertion