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.

Slides:



Advertisements
Similar presentations
PHP SQL. Connection code:- mysql_connect("server", "username", "password"); Connect to the Database Server with the authorised user and password. Eg $connect.
Advertisements

Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Murach's PHP and MySQL, C4© 2010, Mike Murach & Associates, Inc.Slide 1.
Web Database Programming Connecting Database to Web.
PHP and MySQL PHP for the Web, page PHP and MySQL MySQL Resource PHP – MySQL Resource
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Objectives Connect to MySQL from PHP
Multiple Tiers in Action
PHP Scripts HTML Forms Two-tier Software Architecture PHP Tools.
Encrypted Passwords. your_password + username $u = crypt ( your_password ) PHP insert username + $u SQL MySQL database username | encrypted password username.
SJSU CS157B Dr. Lee1  2004 Jenny Mitchell Two Useful Tools You Can’t Live Without by Jenny Mitchell SJSU CS157B Section PHP and MySQL.
Programming with php By: Seth Larson. A little bit about PHP  PHP stands for PHP:  Hypertext Preprocessor  PHP is a widely-used general-purpose server-side.
What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
Class 3 MySQL Robert Mudge Reference:
1 Chapter 8 – Working with Databases spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Slide 8-1 CHAPTER 8 Using Databases with PHP Scripts: Using MySQL Database with PHP.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
INTERNET APPLICATION DEVELOPMENT For More visit:
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
INTERNET APPLICATION DEVELOPMENT PRACTICAL ON CONNECTING TO MYSQL.
MySQL + PHP.  Introduction Before you actually start building your database scripts, you must have a database to place information into and read it from.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
Ways to manage DB in MySQL cs346. Six ways to CREATE and INSERT INTO tables Modelocalremotelocalremotewindow WhereMysql console Putty; Mysql console Mysql.
Introduction to MySQL Lab no. 10 Advance Database Management System.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
MySQL Databases & PHP Integration Using PHP to write data to, and retrieve data from, a MySQL database.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
Database and mySQL Week 07 Dynamic Web TCNJ Jean Chu.
Chapter 9 Using PHP with MySQL. header.html Script 9.1 on page 266 des/header.html
Technology & Management Club Development Software Overview.
PHP with MySQL 1.
MySQL Database Connection
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
Creating PHPs to Insert, Update, and Delete Data CS 320.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Login to a Database (from a Webpage), Inserting data into a database from a form, getting data from database and display on Webpage Done by: Mashail Alsolamy.
PHP Database connectivity Connecting with RDBMS and editing, adding, and deleting databases therein are all done through PHP functions.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
PHP getting data from a MySQL database. Replacing XML as data source with MySQL Previously we obtained the data about the training session from an XML.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
WEB SECURITY WEEK 2 Computer Security Group University of Texas at Dallas.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
Windows 7 WampServer 2.1 MySQL PHP 5.3 Script Apache Server User Record or Select Media Upload to Internet Return URL Forward URL Create.
CHAPTER 10 PHP MySQL Database
>> PHP: MySQL & CRUD. R ecall Database Tables Records is composed of Operations (CRUD) Create Retrieve Update Delete DBMS Access Control MySQL phpMyAdmin.
Unit 1 – Web Concepts Instructor: Brent Presley.
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
 MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications.
Chapter 5 Introduction to SQL.
Introduction to Dynamic Web Programming
Open Source Server Side Scripting Permissions & Users
Web Design and Development
Chapter 9 Using PHP with MySQL.
Introduction to Web programming
PHP + MySQL Commands Refresher.
Accessing Your MySQL Database from the Web with PHP (Ch 11)
PHP: Database connection
Introduction to Web programming
Presentation transcript:

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 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();

PHP Script to Test Database Connection <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Connect to MySQL <?php // Script 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. '; } ?>

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(). ‘ ’);

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’);

PHP Code to Create and Select a DB <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Create the Database <?php // Script 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 ('localhost', 'username', 'password')) { print ' Successfully connected to MySQL. '; if ('CREATE DATABASE myblog')) { print ' The database has been created. '; }

Continued else { die (' Could not create the database because: '. mysql_error(). ' '); } if ('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(). ' '); } ?>

Creating a Table <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Create a Table <?php // Script 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 ('localhost', 'username', 'password')) { if ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' '); } else { die (' Could not connect to MySQL because: '. mysql_error(). ' '); }

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 ($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. ?>

Inserting Data into a DB <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Add a Blog Entry <?php // Script 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 ('localhost', 'username', 'password')) { if ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' '); } else { die (' Could not connect to MySQL because: '. mysql_error(). ' '); }

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 ($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:

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’);

Retrieving Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " View My Blog <?php // Script 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 ('localhost', 'username', 'password')) { if ('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)) {

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. ?>

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.

Deleting Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Delete a Blog Entry <?php // Script 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 ('localhost', 'username', 'password')) { if ('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.

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.

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. ?>

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.

Updating Table Information <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " Edit a Blog Entry <?php // Script 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 ('localhost', 'username', 'password')) { if ('myblog')) { die (' Could not select the database because: '. mysql_error(). ' ');}} else { die (' Could not connect to MySQL because: '. mysql_error(). ' ');}

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.

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. ?>

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’;