PHP I : Database Connections

Follow this lesson in Ullman Chapter 12. The scripts are located in the 12 directory.

For this discussion, you will need to create a testing file. I suggest you call it test.php and save it in your local web root.

As we discuss each code block, you can paste it into test.php and view it (run it) in your browser.

 

Connecting to MySQL

$dbc = mysql_connect (‘hostname’, ‘username’, ‘password’)

Set Up These Values In An Included File That Is Outside Your Web Root!

The dbcon.php file:

<?php
$server = ‘localhost’; // DATABASE SERVER
$database = ‘myblog’; // DATABASE NAME
$user = ‘root’; // USER NAME
$password = ”; // USER PASSWORD
?>

Specifying dbcon.php as an include in your PHP code:

<?
include (‘../../../dbcon.php’);
….
?>

See the script mysql_connect.php in the 12 directory.

 

MySQL Error Handling

mysql_err()

die()

 

// Attempt to connect to MySQL and print out messages.
if ($dbc = mysql_connect (‘localhost’, ‘root’, ”)) {

print ‘<p>Successfully connected to MySQL.</p>’;

mysql_close(); // Close the connection.

} else {

print ‘<p>Could not connect to MySQL.</p>’;

 

// Attempt to connect to MySQL and print out messages.
if ($dbc = @mysql_connect (‘localhost’, ‘root’, ”)) {

print ‘<p>Successfully connected to MySQL.</p>’;

mysql_close(); // Close the connection.

} else {

die (‘<p>Could not connect to MySQL because: <b>’ . mysql_error() . ‘</b></p>’);

}

Note the use of “@” and mysql_error().

 

Creating a Database

Note that you have to connect to the MySQL server before you can create a database within it.

if (@mysql_query (‘CREATE DATABASE myblog’)) {
print ‘<p>The database has been created.</p>’;
} else {
die (‘<p>Could not create the database because: <b>’ . mysql_error() . ‘</b></p>’);
}

 

Selecting a Database

Note that you have to connect to the MySQL server before you can select a database within it.

//Attempt to select a database, after connecting
if (@mysql_select_db (‘myblog’)) {
print ‘<p>The database has been selected.</p>’;
} else {
die (‘<p>Could not select the database because: <b>’ . mysql_error() . ‘</b></p>’);
}

 

Creating a Table

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = ‘CREATE TABLE blog_entries (
blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
entry TEXT NOT NULL,
date_entered DATETIME NOT NULL
)’;

// Run the query.
if (@mysql_query ($query)) {
print ‘<p>The table has been created.</p>’;
} else {
die (‘<p>Could not create the table because: <b>’ . mysql_error() . ‘</b>.</p><p>The query being run was: ‘ . $query . ‘</p>’);
}

 

INSERT INTO: Adding Data

INSERT INTO tablename (column1_name, column2_name, column3_name) values (‘value1’, ‘value2’, ‘value3’)

INSERT INTO tablename values (‘value1’, ‘value2’, ‘value3’)

 

SELECT: Getting Data

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = ‘SELECT title, entry FROM blog_entries ORDER BY date_entered DESC’;

if ($r = mysql_query ($query, $dbc)) { // Run the query.

// Retrieve and print every record.
while ($row = mysql_fetch_array ($r)) {
print “{$row[‘title’]} {$row[‘entry’]}<br />”;
}

} else { // Query didn’t run.
die (‘<p>Could create the table because: <b>’ . mysql_error() . “</b>. The query was $query.</p>”);
}

 

DELETE: Deleting Data

Note that you have to connect to the MySQL server and select a database before you can create or access tables.

// Define the query.
$query = “DELETE FROM blog_entries WHERE blog_id={$_POST[‘id’]} LIMIT 1″;
$r = mysql_query ($query); // Execute the query.

// Report on the result.
if (mysql_affected_rows() == 1) {
print ‘<p>The blog entry has been deleted.</p>’;
} else {
print “<p>Could delete the entry because: <b>” . mysql_error() . “</b>. The query was $query.</p>”;
}

 

UPDATE: Changing Existing Data

Ullman’s Update Script: (edited)

// Define the query.
$query = “UPDATE blog_entries SET title='{$_POST[‘title’]}’, entry='{$_POST[‘entry’]}’ WHERE blog_id={$_POST[‘id’]}”;
$r = mysql_query ($query); // Execute the query.

// Report on the result.
if (mysql_affected_rows() == 1) {
print ‘<p>The blog entry has been updated.</p>’;
} else {
print “<p>Could update the entry because: <b>” . mysql_error() . “</b>. The query was $query.</p>”;
}

 

Close Your Database Connection!

ALWAYS close your database connection at the end of your script!

mysql_close()

That’s all it takes.

 

To do out of class:

Review Chapter 12 of Ullman.