CSC 2720 Building Web Applications Accessing MySQL from PHP.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
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.
Web Database Programming Connecting Database to Web.
Nic Shulver, Introduction to SQL Topics covered Structured Query Language What can it do? Advantages of SQL Why bother with SQL?
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
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
PHP and MySQL Web Development tMyn1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in.
Website Development Working with MySQL. What you will achieve today! Connecting to mySql Creating tables in mySql Saving data on a server using mySql.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
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,
MIS Week 11 Site:
LIS651 lecture 7 PHP mySQL Thomas Krichel
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Create an online booking system (login/registration)
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
Sayed Ahmed Computer Engineering, BUET, Bangladesh MSC, Computer Science, U of Manitoba, Canada
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Nic Shulver, Retrieving Stored Data Introduction This set of slides shows: The information source database structure The data.
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.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
What is MySQLi? Since the mid-90s, Mysql extension has served as the major bridge between PHP and MySQL. Although it has performed its duty quite well,
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
CSC 2720 Building Web Applications Database and SQL.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Chapter 9 Using PHP with MySQL. header.html Script 9.1 on page 266 des/header.html
(Chapter 10 continued) Our examples feature MySQL as the database engine. It's open source and free. It's fully featured. And it's platform independent.
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
PHP with MySQL 1.
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
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.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting MySQL – Inserting Data.
2010/11 : [1]PHP with MySQLBuilding Web Applications using MySQL and PHP (W1) PHP with MySQL.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
PHP: MySQL. PHP Connect to MySQL PHP 5 and later can work with a MySQL database using: – MySQLi extension (the "i" stands for improved) – PDO (PHP Data.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
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.
MySQL MySQL and PHP – interacting with a database.
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in PHP consists of a number of functions.
 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.
Nic Shulver, Storing Data on the Server Introduction We are going to look at some working code It writes fixed data into a simple.
Web Systems & Technologies
Web Database Programming Using PHP
PHP (Session 2) INFO 257 Supplement.
PHP: MySQL Lecture 14 Kanida Sinmai
Web Database Programming Using PHP
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Chapter 9 Using PHP with MySQL.
Introduction to Web programming
Objectives Connect to MySQL from PHP Learn how to handle MySQL errors
ISC440: Web Programming 2 Server-side Scripting PHP 3
MySQL Web Application Connecting to a MySQL database
Tutorial 6 PHP & MySQL Li Xu
MySQL Web Application Connecting to a MySQL database
Introduction to Web programming
Presentation transcript:

CSC 2720 Building Web Applications Accessing MySQL from PHP

Outline 1.Connecting to MySQL 2.Executing Queries 3.Example: Adding a Record 4.Retrieving Query Results 5.Escaping Special Characters 6.Counting Returned or Affected Records 7.Using Prepared Statements

Connecting to MySQL  Line 8: mysqli_connect() connects to a MySQL server running at DB_HOST and selects the database DB_NAME. Upon success, $dbc holds a reference to the database which is needed by subsequent mysqli_* function calls. // Define named constants DEFINE('DB_USER', 'username'); DEFINE('DB_PASSWORD', password'); DEFINE('DB_HOST', 'localhost'); DEFINE('DB_NAME', 'database_name'); // Establish connection $dbc ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ) OR exit('Could not connect to MySQL: '. mysqli_connect_error());

Connecting to MySQL  Line is en error suppression operator. It prevents the PHP error (when mysqli_connect() encounters an error) from being produced in the output.  The user don't need to see the error message.  Line 10: " expr1 OR expr2 " means "If expr1 is true, don’t evaluate expr2 ).  This kind of evaluation is called short circuit evaluation.  So at line 10, exit() will only be called if mysqli_connect() fails.  Line 10: exit($message) outputs the value of $message and terminates.  Line 11: mysqli_connect_error() returns a string containing a detailed error message about the failed connection.

Executing Queries  Line 2: mysqli_query() sends a query to a server. It returns TRUE (or a result object for SELECT, SHOW, DESCRIBE, and EXPLAIN commands) on success or FALSE on failure. $query = "…"; // An SQL query string $result $query); if ($result) { // Success } else { $error_msg = mysqli_error($dbc); // Handle error here } mysqli_close($dbc);

Executing Queries  Line 8: mysqli_error() returns a string containing a detailed error message about the failed query operation.  Line 12: mysqli_close() closes the database connection.  If you don't close a database connection explicitly, the system will close it automatically when the script terminates. By closing a database connection explicitly as soon as you finished using it, the database can use the freed connection and resource to serve other requests.

Example: Adding a Record $fn = "John"; $ln = "Doe"; $ = $pwd = " "; $q = "INSERT INTO users ". "(first_name, last_name, , pass, reg_date)". "VALUES ". "('$fn', '$ln', '$ ', SHA1('$pwd'), NOW())"; $result $q); if (!$result) { $err[] = "Fail to add user: ". mysqli_error($dbc); } mysqli_close($dbc);

Example: Adding a record  Line 1-4: In practice these values are usually obtained from a HTML form.  Line 9: SHA1() is an MySQL function that performs a one- way encryption on its parameter and returns a 40- character long encrypted string.  It is safer to store a password as encrypted string than as plain text  To compare passwords, you will need to compare the encrypted version.  Line 9: NOW() is a function that returns the current date and time of the MySQL server (not the Web server).

Retrieving Query Results $q = "SELECT * FROM users"; $result $q); while ($row = mysqli_fetch_array($result)) { // $row is both an associative array and a numeric array $fname = $row['first_name']; // Assuming the 3 rd column corresponds to 'last_name' $lname = $row[2]; … } mysqli_free_result($result); mysqli_close($dbc);

Retrieving Query Results  Line 2: A "SELECT" query returns a result set that contains multiple rows. For such command, mysqli_query() returns a reference to the result set.  We can only retrieve one row of results at a time.  Line 4: mysqli_fetch_array($result) returns the current row as an array (which can be processed as an associative or a numeric array). The function returns NULL when no more row is available.  Line 15: mysqli_free_result($result) frees the resource used by $result.

Retrieving Query Results  Related functions:  mysqli_fetch_row() – returns the result set as a numeric array  mysqli_fetch_assoc() – returns the result set as an associative array  mysqli_fetch_object() – returns the result set as an object  mysqli_data_seek() -- adjusts the result pointer to an arbitary row in the result set  Use different variables to hold the results of different queries. $result $q1); while ($row = mysqli_fetch_row($result)) { // Should use a different variable to hold the result $result $q2); … }

Escaping Special Characters  Before using an input string in an SQL query, you should make sure all the special characters in the string are properly escaped.  mysqli_real_escape_string($dbc, $data) returns a string containing all the characters in $data but with all the special characters in $data properly escaped.

Counting Returned or Affected Records  mysqli_num_rows($result) returns the total number of rows in a result set returned by a SELECT query.  You can use this function to help you figure out if a SELECT command retrieves any row before starting to fetch anything from the result set.  mysqli_affected_rows($dbc) returns the total number of rows affected by an INSERT, UPDATE, or DELETE query.  You can use this function to check if your command achieve its objective. e.g., is a DELETE command deleting exactly one row?

Using Prepared Statements  With a prepared query, the SQL syntax is sent to MySQL first for "compilation". Then the specific values are sent separately.  Advantage of prepared statements are  Greater security  Potentially better performance

Using Prepared Statements  Without prepared statement: $q = "SELECT first_name, last_name FROM users ". "WHERE last_name=$lname"; $result = mysqli_query($q);  As prepared statement: $q = "SELECT first_name, last_name FROM users ". "WHERE last_name=?"; $stmt = mysqli_prepare($dbc, $q); mysqli_stmt_bind_param($stmt, 's', $lname); mysqli_stmt_execute($stmt);

Using Prepared Statements $q = "SELECT first_name, last_name FROM users ". "WHERE last_name=?";  ? serves as a placeholder in the query $stmt = mysqli_prepare($dbc, $q);  Requests the server to compile the query mysqli_stmt_bind_param($stmt, 's', $lname);  Substitute the value of $lname into the location of the placeholder. 's' indicates the value is a string. ('d' for decimal, 'i' for integer, 'b' for binary data.) mysqli_stmt_execute($stmt);  Execute the query

Example: Using Prepared Statements $q = 'INSERT INTO users '. '(first_name, last_name, , pass, reg_date)'. ' VALUES (?, ?, ?, SHA1(?), NOW())'; $stmt = mysqli_prepare($dbc, $q); // Assume $users is an array containing the data of // several users for ($i = 0; $i < count($users); $i++) { mysqli_stmt_bind_param($stmt, 'ssss', $users['fname'], $users['lname'], $users[' '], $users['password']); mysqli_stmt_execute($stmt); } …

References and Resources  MySQL   PHP Manual for MySQL Improved Extension   PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition), by Larry Ullman. Peachpit Press, 2007