PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.

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

Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Learning XML Erik T. Ray CSCI 305 Introduction to Database.
PHP –Writing Reusable Code 10 March 2006 Adina Crainiceanu IT420: Database Management and Organization.
Faculty of Sciences and Social Sciences HOPE PHP & MySQL Stewart Blakeway FML 213
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
PHP (2) – Functions, Arrays, Databases, and sessions.
Objectives Connect to MySQL from PHP
PHP Scripts HTML Forms Two-tier Software Architecture PHP Tools.
COM621 – Lecture 5 MySQL and PHP Integration. PHP - MySQL Commercial Sites: – Apache – PHP – MySQL – XAMP (WAMP – MAMP) Required Tools – Text Editor or.
PHP Programming. Topics Background and History of PHP Installation Comments in PHP Variables Conditions Loops Functions File Handling Database Handling.
SJSU CS157B Dr. Lee1  2004 Jenny Mitchell Two Useful Tools You Can’t Live Without by Jenny Mitchell SJSU CS157B Section PHP and MySQL.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Advance Database Management Systems Lab no. 5 PHP Web Pages.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Session 5: Working with MySQL iNET Academy Open Source Web Development.
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:
Create an online booking system (login/registration)
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.
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.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
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.
Week 7. Lecture 2 Functions, Arrays, PHP&MySQL. Function with More than one argument and a return statement For a function to return a value, the return.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 10 – MYSQL and PHP (Part 2)
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.
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
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.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
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.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
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.
U:/msu/course/cse/103 Day 21, Slide 1 CSE 103 Makeups –If you didn’t take one over the weekend, take one TUESDAY or WEDNESDAY!
Accessing mySQL relational database. MySQL database.  Today, we will attempt and open a connection to the MySQL server.  We need to specify the database.
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.
MySQL MySQL and PHP – interacting with a database.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP and SQL Server: Connection IST 210: Organization of Data IST2101.
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
Web Database Programming Using PHP
Web Database Programming Using PHP
Storing Images Connect to the server using the correct username and password. $conn = mysql_connect(“yourserver”, “joeuser”, “yourpass”); Create the database.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Database application MySQL Database and PhpMyAdmin
ISC440: Web Programming 2 Server-side Scripting PHP 3
Web Programming Language
PHP: Database connection
Tutorial 6 PHP & MySQL Li Xu
Web Programming– UFCFB Lecture
Presentation transcript:

PHP+MySQL Integration

Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds the content of the page PHP has several libraries that allows for communication with many different databases Some of these libraries have variations in the commands We will be using the mysql library Most functions start with mysql_ and then the name of the function 2

Working with databases –key steps 1.Design the DB – Create the DB on PHPMyAdmin or MySQL command 2.Design and create the HTML 3.Create a connection and select the database 4.Run the query – Verify Insert/Fetch the rows/Do other SQL associated tasks 5.Display Results as needed 6.Close the connection 3

1. Database Design and Creation Create database ‘hospital’, add a table ‘discharge’ with appropriate fields – patient id, name, appointment type, admission ward, xray examination, mri scan, cat scan, eye test, hearing test, and date (to capture todays date) hospital discharge (patid,name, appointment, ward, xray, mri, cscan, eye, hearing, date)

Data details FieldTypeComment patidint(11) NN AI PKPrimary Key Index namevarchar(45)Patient Full Name appointmentvarchar(11)type of appointment: GP, Specialist or Surgery wardchar(2)Admitted to ward? No, or ward A,B or C xraychar(3)x-rays taken? YES,NO mrichar(3)mri carried out? YES,NO cscanchar(3)CAT scan carried out? YES,NO eyechar(3)eye test carried out? YES,NO hearingchar(3)hearing test carried out? YES,NO date date of discharge: format YYYY-MM-DD as text

2. Design and Create the HTML In order to interact with the database we need a data capture form, and a script that will process the form. Create an HTML document in the folder you created in C:\wamp\www, and save it as hospital.html

hospital.html Patient name: Appointment type: GP Specialist Surgery Admission to these Wards: No Ward Ward A Ward B Ward C Treatments Undertaken: X-Ray Treatment MRI Scan CAT Scan Eye Test Hearing Test

Form link to php script file use get to check form is working correctly post could also be used, user choice form name

Drop down list Patient Name: Appointment type General Practicioner Specialist Surgery 3 options for appointment type

Radio buttons Admission to Wards: No Ward Ward A Ward B Ward C 4 options via radio buttons, only one can be selected on form

Checkboxes Treatments Undertaken: X-Ray Treatment MRI Scan CAT Scan Eye Test Hearing Test 5 options, any can be selected on form

Submit/reset buttons

process.php <?php $name = $_GET['name']; $app = $_GET['appointment']; $ward = $_GET['ward']; $variable single option data passing $_POST option also viable, keep consistent with previous use Open a new file, save as process.php, keep on same directory as html file Arguments are passed as below:

Checkbox data selection if (isset($_GET['xray'])) { $xray = $_GET['xray']; } else { $xray = "No"; } Note: This code needs to be repeated for every checkbox variable passed as a parameter the variables used are: $mri, $cscan, $eye, $hearing checkboxes allow multiple options if not checked, it will not pass the parameter (not set) if passed the default is set to ‘yes’ so if not passed, we need to assign a value to the respective variable that will go into the database

Check data capture print "Name:".$name." "; print "Appointment:".$app." "; print "Ward:".$ward." "; print "X-Ray:".$xray." "; print "MRI:".$mri." "; print "CSCAN:".$cscan." "; print "EYE:".$eye." "; print "HEARING:".$hearing." "; print used to check fields are being passed and captured in the page

3. Database connection You will need: – The address to the database server – A username with privileges to access the table you require – The username associated password Optionally: – The name of the database you are connecting to 16

Connection Sequence mysql_connect(host, username, password) – returns a link to the host using username and password authentication. Usage: – $conn=mysql_connect(‘localhost’,myusername’,’MyP455w0rd’); mysql_select_db(database,link) – selects a database from the connection in link Usage: – mysql_select_db(‘db_name’,$conn); 17

Opening a connection $link = mysql_connect('localhost','student','student') or die(mysql_error()); mysql_select_db('hospital',$link);

Current date selection $querydate = "SELECT CURDATE() as Today"; $result1 = mysql_query($querydate,$link) or die(mysql_error()); $row = mysql_fetch_assoc($result1); $today = $row['Today']; This script demonstrates how the current date can be obtained from the MySQL server using the appropriate DATE query The parameter being queried (date) does not have an index in the array, so we need to use the alias “AS” to assign an index that we can use to retrieve from the result array

4. Run the query mysql_query(link, query) is used to run a query on the database server. It requires the link and the query string and returns a result object. Usage: $result= mysql_query(“SELECT * from directory”, $conn); Queries can be constructed as strings. The string variable can then be used on the mysql_query command. Usage: $query="select * from directory"; $result = mysql_query($query,$link) or die("could not execute:".mysql_error());

Insert query $query = "INSERT INTO discharge VALUES (NULL,'$name','$app','$ward','$xray','$mri','$cscan','$eye','$hearing','$today')"; $result = mysql_query($query,$link) or die(mysql_error()); $affected = mysql_affected_rows($link); if ($affected >0) {echo "success";} else {echo "fail";} detects affected rows in the query in this case 1 row was INSERTED so $affected=1 if the insert was successful generates mysql error causes Query to insert all data from html form + date obtained from previous query Specify discharge table

Select query $query3 = "SELECT * FROM discharge"; $result3 = mysql_query($query3,$link) or die(mysql_error()); $row3 = mysql_fetch_assoc($result3); ?> This query will retrieve all the data from the table discharge

5. Display results Result sets are objects. They point to places in memory where the values returned from the query exist Result sets are NOT the individual rows from the query You can think of a result set as the TABLE that holds the results You need to read the rows from that table individually $row=mysql_fetch_array($result); Using this function, the array returned can be either numerically indexed or associative! If there are no more rows, the function returns FALSE

Table headings Patient ID Patient Name Appointment Type Admitted to Ward X-Ray MRI Cat Scan Eye Test Hearing Test Date Discharged

Results $row is an associative array containing the results, the index of the array is the field in the database

do …. while loop DO-WHILE Loop needed to display all the results of the database

Keeping it tidy Once you have completed your work with the database, there are two things you should do: – Free the results – Close the connection to the server. Freeing the results can be optional: On closing the connection, the results are automatically freed If you are planning to run further queries on the same connection, it is good practice to free the previous result set. – mysql_free_result($result); To close the connection you use – mysql_close($conn); 27

6. Close connection <?php mysql_close($link); ?>

Places where things can go wrong Creating a connection – Server unreachable/offline – Wrong username/password combination Selecting the table – Table does not exist – User without privileges for that table Running the query – Syntax errors – Empty result set Fetching results – Misusing the array 29