"> ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP and MySQL Database. Connecting to MySQL Note: you need to make sure that you have MySQL software properly installed on your computer before you attempt.

Similar presentations


Presentation on theme: "PHP and MySQL Database. Connecting to MySQL Note: you need to make sure that you have MySQL software properly installed on your computer before you attempt."— Presentation transcript:

1 PHP and MySQL Database

2 Connecting to MySQL Note: you need to make sure that you have MySQL software properly installed on your computer before you attempt to make a connection. You also need to have a user name and password. Syntax for connecting to a database is: $dbc = mysql_connect (‘localhost’, ‘username’, ‘password’); Once you are done working with the DB close the connection: mysql_close();

3 PHP Script to Test Database Connection <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Connect to MySQL <?php // Script 12.1 - mysql_connect.php (This script connects to the MySQL server). // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Attempt to connect to MySQL and print out messages. if ($dbc = mysql_connect ('localhost', 'username', 'password')) { print ' Successfully connected to MySQL. '; mysql_close(); // Close the connection. } else { print ' Could not connect to MySQL. '; } ?>

4 MySQL Error Handling Common errors you will encounter are: Failure to connect to MySQL Failure in selecting a database Inability to run a query No results being returned by a query Data not being inserted into a table Using mysql_error() function returns a textual version of the error that the MySQL server returned: Die (‘ Could not connect to MySQL because: ’. Mysql_error(). ‘ ’);

5 Creating and Selecting a Databse To create a database with PHP use: mysql_query(‘CREATE DATABASE mydatabase’); To select the database use: Mysql_select_db(‘mydatabase’);

6 PHP Code to Create and Select a DB <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Create the Database <?php // Script 12.3 - create_db.php (This script connects to the MySQL server. It also creates and selects the database. // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Attempt to connect to MySQL and print out messages. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { print ' Successfully connected to MySQL. '; if (@mysql_query ('CREATE DATABASE myblog')) { print ' The database has been created. '; }

7 Continued else { die (' Could not create the database because: '. mysql_error(). ' '); } if (@mysql_select_db ('myblog')) { print ' The database has been selected. '; } else { die (' Could not select the database because: '. mysql_error(). ' '); } mysql_close(); // Close the connection. } else { die (' Could not connect to MySQL because: '. mysql_error(). ' '); } ?>

8 Creating a Table <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Create a Table <?php // Script 12.4 - create_table.php (This script connects to the MySQL server, selects the database, and creates a table). // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Connect and select. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { if (!@mysql_select_db ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' '); } else { die (' Could not connect to MySQL because: '. mysql_error(). ' '); }

9 Continued // 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 ' The table has been created. '; } else { die (' Could not create the table because: '. mysql_error(). '. The query being run was: '. $query. ' ');} mysql_close(); // Close the connection. ?>

10 Inserting Data into a DB <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Add a Blog Entry <?php // Script 12.5 - add_entry.php (This script adds a blog entry to the database). // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset ($_POST['submit'])) { // Handle the form. // Connect and select. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { if (!@mysql_select_db ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' '); } else { die (' Could not connect to MySQL because: '. mysql_error(). ' '); }

11 Continued // Define the query. $query = "INSERT INTO blog_entries (blog_id, title, entry, date_entered) VALUES (0, '{$_POST['title']}', '{$_POST['entry']}', NOW())"; // Execute the query. if (@mysql_query ($query)) { print ' The blog entry has been added. '; } else { print " Could not add the entry because: ". mysql_error(). ". The query was $query. "; } mysql_close(); } // Display the form. ?> Entry Title: Entry Text:

12 Retrieving Data from a Database Retrieved information must be assigned to a variable: $query = ‘SELECT * FROM tablename’; You may use the WHERE clause to restrict which records to be retrieved:$query = ‘SELECT Lname, Fname FROM employees WHERE (dept = ‘sales’);

13 Retrieving Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> View My Blog <?php // Script 12.6 - view_blog.php // This script retrieves blog entries from the database. // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Connect and select. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { if (!@mysql_select_db ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' ');}} else { die (' Could not connect to MySQL because: '. mysql_error(). ' ');} // Define the query. $query = 'SELECT * FROM blog_entries ORDER BY date_entered DESC'; if ($r = mysql_query ($query)) {

14 Code Continued // Run the query. // Retrieve and print every record. while ($row = mysql_fetch_array ($r)) { print " {$row['title']} {$row['entry']} Edit Delete \n";}} else { // Query didn't run. die (' Could not retrieve the data because: '. mysql_error(). ". The query was $query. ");} // End of query IF. mysql_close(); // Close the database connection. ?>

15 Deleting Data The syntax is: DELETE FROM tablename WHERE column=value LIMIT 1; Function mysql_affected_rows() returns the number of rows affected by an insert, delete or update query.

16 Deleting Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Delete a Blog Entry <?php // Script 12.7 - delete_entry.php // This script deletes a blog entry. // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Connect and select. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { if (!@mysql_select_db ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' ');}} else { die (' Could not connect to MySQL because: '. mysql_error(). ' ');} if (isset ($_POST['submit'])) { // Handle the form.

17 Code Continued // 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 ' The blog entry has been deleted. ';} else { print " Could not delete the entry because: ". mysql_error(). ". The query was $query. ";}} else { // Display the entry in a form. // Check for a valid entry ID in the URL. if (is_numeric ($_GET['id']) ) { // Define the query. $query = "SELECT * FROM blog_entries WHERE blog_id={$_GET['id']}"; if ($r = mysql_query ($query)) { // Run the query. $row = mysql_fetch_array ($r); // Retrieve the information.

18 Code Continued // Make the form. print ' Are you sure you want to delete this entry? '. $row['title']. ' '. $row['entry']. ' ';} else { // Couldn't get the information. print " Could not retrieve the entry because: ". mysql_error(). ". The query was $query. ";}} else { // No ID set. print ' You must have made a mistake in using this page. ';}} // End of main IF. mysql_close(); // Close the database connection. ?>

19 Updating Data in a Database WHERE clause must be used or all the records in the database will be updated. If the values are strings they should be placed between single quotation marks.

20 Updating Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Edit a Blog Entry <?php // Script 12.8 - edit_entry.php // This script edits a blog entry using an UPDATE query. // Address error handling. ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); // Connect and select. if ($dbc = @mysql_connect ('localhost', 'username', 'password')) { if (!@mysql_select_db ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' ');}} else { die (' Could not connect to MySQL because: '. mysql_error(). ' ');}

21 Code Continued if (isset ($_POST['submit'])) { // Handle the form. // 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 ' The blog entry has been updated. ';} else { print " Could not update the entry because: ". mysql_error(). ". The query was $query. ";}} else { // Display the entry in a form. // Check for a valid entry ID in the URL. if (is_numeric ($_GET['id']) ) { // Define the query. $query = "SELECT * FROM blog_entries WHERE blog_id={$_GET['id']}"; if ($r = mysql_query ($query)) { // Run the query. $row = mysql_fetch_array ($r); // Retrieve the information.

22 Code Continued // Make the form. print ' Entry Title: Entry Text: '. $row['entry']. ' ';} else { // Couldn't get the information. print " Could not retrieve the entry because: ". mysql_error(). ". The query was $query. ";} else { // No ID set. print ' You must have made a mistake in using this page. ';}} // End of main IF. mysql_close(); // Close the database connection. ?>

23 How to Create Users and Privileges in MySQL Open the MySQL monitor and type the following: mysql> GRANT privileges ON database.* TO username IDENTIFIED BY ‘password’; Example: mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER ON companydb.* TO areej IDENTIFIED BY ‘aa7097’;


Download ppt "PHP and MySQL Database. Connecting to MySQL Note: you need to make sure that you have MySQL software properly installed on your computer before you attempt."

Similar presentations


Ads by Google