1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.

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.
PHP and MySQL PHP for the Web, page PHP and MySQL MySQL Resource PHP – MySQL Resource
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
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.
1 CS428 Web Engineering Lecture 23 MySQL Basics (PHP - VI)
PHP-MySQL By Jonathan Foss. PHP and MySQL Server Web Browser Apache PHP file PHP MySQL Client Recall the PHP architecture PHP can communicate with a MySQL.
Check That Input Preventing SQL Injection Attacks By Andrew Morton For CS 410.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
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.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
LIS651 lecture 7 PHP mySQL Thomas Krichel
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.
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.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
Sayed Ahmed Computer Engineering, BUET, Bangladesh MSC, Computer Science, U of Manitoba, Canada
PHP – MySQL Extensions. Table used in most examples CREATE TABLE product ( rowID INT NOT NULL AUTO_INCREMENT, productid VARCHAR(8) NOT NULL, name VARCHAR(25)
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Mark Dixon Page 1 23 – Web applications: Writing data to Databases using PhP.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
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.
PHP MySQL. SQL: Tables CREATE TABLE tablename { fieldname type(length) extra info,... } Extra info: –NULL (allows nulls in this field) –Not NULL (null.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and 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.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
Lecture 10 – MYSQL and PHP (Part 2)
(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.
Database Access with PHP and MySQL CS356 Examples from Web Database Applications, by Hugh E. Williams & David Lane, O'Reilly, 2002.
PHP with MySQL 1.
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
Internet Information Systems Writing to Databases and Amending Data.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Pengantar Teknologi Internet W14: Server Scripting & Database.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
Creating PHPs to Insert, Update, and Delete Data CS 320.
PHP PHP: Hypertext Preprocesor Personal Home Page Tools.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
2010/11 : [1]PHP with MySQLBuilding Web Applications using MySQL and PHP (W1) PHP with MySQL.
PHP Database connectivity Connecting with RDBMS and editing, adding, and deleting databases therein are all done through PHP functions.
PHP Database Processing CIS 1715 Web Technologies.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
PHP and SQL Server: Connection IST2101. Typical web application interaction (php, jsp…) database drivers 2IST210.
Accessing mySQL relational database. MySQL database.  Today, we will attempt and open a connection to the MySQL server.  We need to specify the database.
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CSC 2720 Building Web Applications Accessing MySQL from PHP.
CSC 405: Web Application Engineering II8.1 Web programming using PHP What have we learnt? What have we learnt? Underlying technologies of database supported.
PHP and SQL Server: Connection IST 210: Organization of Data IST2101.
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.
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Web Systems Development (CSC-215)
Erasmus Exchange in Ionian University
PHP: Database connection
Web Programming– UFCFB Lecture
Database Access with PHP and MySQL
Presentation transcript:

1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices

 PHP supports about 20 RDBM servers  Including MySQL, Oracle, MS SQL, DB2, Firebird and Paradox  Supports connection over ODBC driver  Provided different sets of functions for accessing the different RDBMS  Each function starts with prefix – the DB server type Example: mysql_connect, mssql_query, etc

 mysql_connect – function to connect to MySQL server  Parameters: $server, $username, $password, $new_link, $client_flags  Returns resource result, identifying the new link (link identifier)  The result is used as parameter to other mysql_ functions mysql_connect("localhost", "root", "rootpass");

 Once connected a database must be selected to perform queries upon  In some cases it is not required – show databases query for instance  mysql_select_db ($dbname, $link) – selects database from the server  Returns true if successful $dblink = mysql_connect("local host", "root", "rootpass"); mysql_select_db("mydb", $dblink); $dblink = mysql_connect("local host", "root", "rootpass"); mysql_select_db("mydb", $dblink);

Connecting to DB Live Demo

 mysql_query ($query, $link) – execute query on database  $query is string – the query to be executed  $link is database link identifier  The returned result depends on the query  If query is select, show, describe, explain – returns resource or false on error  Otherwise true if successful, false on error  The link parameter can be omitted in all mysql_ functions if working with only one database  Only one call to msql_connect in the script mysql_query("select * from users", $dblink);

 PHP provides several functions for working with MySQL select query results  mysql_query returns resource when performing select query that holds the data  The result is accessed row-per-row from first towards last with internal pointer  Additional functions to get number of affected rows on update/delete or auto-generated id of inserted row

 mysql_fetch_row – returns numerical array, containing the current row from the result and moves the pointer to the next row  Returns false if there are no more rows $res = mysql_query ("select id, name from people"); $row = mysql_fetch_row($res); if ($row) print_r($row); // 0->id, 1->name else echo "No results!"; $res = mysql_query ("select id, name from people"); $row = mysql_fetch_row($res); if ($row) print_r($row); // 0->id, 1->name else echo "No results!";

MySQL Query Live Demo

 mysql_fetch_assoc – returns associative array containing the current row in result and moved the pointer to the next one  The field names are keys in the array  Returns false if no more rows $res = mysql_query ("select id, name from people"); $row = mysql_fetch_assoc($res); if ($row) echo "Name: ".$row['name']; $res = mysql_query ("select id, name from people"); $row = mysql_fetch_assoc($res); if ($row) echo "Name: ".$row['name'];

Live Demo

 mysql_result ($result, $row, $field) – return the value or single cell In MySQL query result  $field is either field index or name  Returns false on failure  Must NOT be mixed with other functions for reading query result  Much slower than fetching data row-per-row $res = mysql_query ("select count(*) from people"); echo mysql_result($res, 0, 0); $res = mysql_query ("select count(*) from people"); echo mysql_result($res, 0, 0);

mysql_result Live Demo

 mysql_num_rows ($result) – returns the number of rows in the result set  Does not work with unbuffered queries ( mysql_unbuffered_query ) $res = mysql_query ("select id, name from people"); $count = mysql_num_rows($res); echo $count; $res = mysql_query ("select id, name from people"); $count = mysql_num_rows($res); echo $count;

mysql_num_rows Live Demo

 mysql_data_seek ($result, $row) – changes the position of the internal pointer in the result  Allows you to reuse result once fetched with mysql_fetch_* functions  Returns true on success, false on failure $res = mysql_query ( … ); $count = mysql_num_rows($res); for ($i = $count - 1; $i >= 0; $i--) { mysql_data_seek($res, $i); $row = mysql_fetch_assoc($res); print_r($row);} $res = mysql_query ( … ); $count = mysql_num_rows($res); for ($i = $count - 1; $i >= 0; $i--) { mysql_data_seek($res, $i); $row = mysql_fetch_assoc($res); print_r($row);}

Live Demo

 mysql_insert_id($link) – get the auto generated ID of previous insert/replace query  Returns 0 if no ID was generated, false on error  Works only for AUTO_INCREMENT columns  $link can be omitted if only one link established mysql_query ("insert into people ("name", "age") values ("To6ko", "30"); echo mysql_insert_id(); mysql_query ("insert into people ("name", "age") values ("To6ko", "30"); echo mysql_insert_id();

mysql_insert_id Live Demo

 mysql_affected_rows($link) – returns number of affected rows in most recent insert/update/delete/replace query  As with all mysql_ functions $link can be omitted if only one link established  Returns -1 if last query failed mysql_query ("update people set age+1 where age < 20"); echo mysql_insert_id(); mysql_query ("update people set age+1 where age < 20"); echo mysql_insert_id();

 mysql_errno ($link) - returns the error code from the last query  Returns 0 if no error occurred  mysql_error ($link) – returns the error text from the last query  Returns empty string if no error occurred mysql_query ("insert into nosuchtable"); echo mysql_errno().": ".mysql_error(); mysql_query ("insert into nosuchtable"); echo mysql_errno().": ".mysql_error();

 mysql_free_result($resource) – clears the memory occupied by select query result  mysql_close($link) – closes connection to mysql server  When PHP script ends all resources are freed automatically and all connections – closed  Freeing is not necessary  Closing is needed only when using persistent connections

 Persistent connections are connections that are kept open after script ends  Allows reusing  Saves time for next script to connect  Very useful for slow-login databases (MS SQL, Firebird, etc)  When performing persistent connect PHP searches for already opened connection and reuses it  mysql_pconnect – similar to mysql_connect but checks for previous persistent connection with same parameters and reuses it

 All strings that are generated from user input must be escaped  Quotes, double quotes and back slashes must be prefixed with back slash  Lack of escaping may lead to errors and security issues  mysql_real_escape_string – returns given string with characters escaped, taking into account the character set of the connection  When using Cyrillic this may escape the Cyrillic characters and turn them into hex codes  Escaping may be done by simple string replacement or with regular expressions

 Example escaping with string replacement  When the string, inserted in the DB is going to be printed to a page, using htmlentities is good idea  Replaces all HTML special chars with their entities  Can be set to include quotes and double quotes  Second parameter sets quotes converting mysql_query ("insert into people values (null, '.str_replace("'","\\'",$_POST['name'])'"); htmlentities("пробваме ', \", &^%", ENT_QUOTES);

Questions?

1. Create a PHP script to show a database table rows as HTML table. 2. Create PHP application that implements very simple message board. First create MySQL database and table messages(msg_id, msg_text, msg_date). Implement the following functionality:  Displaying table rows  Adding rows  Deleting rows 3. Implement table paging for previous exercise.