COM621 – Lecture 5 MySQL and PHP Integration. PHP - MySQL Commercial Sites: – Apache – PHP – MySQL – XAMP (WAMP – MAMP) Required Tools – Text Editor or.

Slides:



Advertisements
Similar presentations
PHP: Date() Function The PHP date() function formats a timestamp to a more readable date and time.
Advertisements

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.
Introduction to Structured Query Language (SQL)
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
Intermediate PHP & MySQL
Introduction to Structured Query Language (SQL)
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
© 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.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
COM336 Web Database Development Open Source Database Systems.
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:
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
ASP.NET Programming with C# and SQL Server First Edition
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
PHP MySQL Introduction
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
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.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting MySQL – Selecting Data.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
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)
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.
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
ADVANCED SQL.  The SQL ORDER BY Keyword  The ORDER BY keyword is used to sort the result-set by one or more columns.  The ORDER BY keyword sorts the.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
1.Switch on the computer and wait for loading. 2.Select the Windows 7 OS at the end of the list. 3.Click on the link ‘Administrator’ 4.Enter the administrator.
SQL Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
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.
Web Systems & Technologies
Chapter 5 Introduction to SQL.
 2012 Pearson Education, Inc. All rights reserved.
JDBC.
ISC440: Web Programming 2 Server-side Scripting PHP 3
SQL Tutorial.
Chapter 8 Working with Databases and MySQL
CIS16 Application Programming with Visual Basic
Sirena Hardy HRMS Trainer
Introduction To Structured Query Language (SQL)
Tutorial 6 PHP & MySQL Li Xu
Presentation transcript:

COM621 – Lecture 5 MySQL and PHP Integration

PHP - MySQL Commercial Sites: – Apache – PHP – MySQL – XAMP (WAMP – MAMP) Required Tools – Text Editor or a Program like Dreamweaver

Installing XAMP If you are working from your laptop, it is time to download and install XAMP: – Windows: Download and Install WAMP Server – MAC: Download and Install MAMP – Leave all the settings as default except the browser (change to your preferred browser: I recommend Chrome, Firefox or Safari) – Once Installed, your files for this module need to be stored in the following folder (also applies to the lab machines: c:/wamp/www – Task: Create a folder with your name inside this folder

Stopping IIS Next step (only if you are working in the lab) – you need to stop IIS – go to: – CONTROL PANEL  ADMINISTRATIVE TOOLS  Internet Information Service (IIS) Manager 

Stopping IIS – At the top right hand side of the screen click STOP

Configuring XAMP Now is time to Start WAMP Server: – On the desktop click start wampserver; a red “w” icon should appear in your taskbar, it should go from red, to orange to green – once it is green we are ready to go

Starting WAMP Start WampServerTaskBar – Red “W”

Starting WAMP Right click on the icon and select: localhost (this should open your browser with the WAMP welcome page)

WAMP in Browser

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 10

Opening a 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 11

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

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

Working with the results from the query Result sets are objects. They point to places in memory where the query returned values exist Result set 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 14

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

Working with databases – key steps Design the DB – Create the DB on PHPMyAdmin or MySQL command Design and Create the HTML Create a connection Select the table Run the query Verify Insert/Fetch the rows/Do other SQL associated tasks Display Results as needed Close the connection 16

MySQL – Data Manipulation Language

SQL Data Manipulation Language (DML) SQL is a non procedural language providing syntax for extracting data, including a syntax to update, insert, and delete records. The Query and Update commands together form the Data Manipulation (DML) part of SQL – SELECT – UPDATE – DELETE – INSERT INTO

SQL-DML SELECT SELECT: This command is mandatory when performing a query; it is used to retrieve data from a table based on some criteria It specifies a coma separated list of fields to be retrieved, and the FROM clause specifies the table(s) to be accessed. The results are stored in a result table known as the result-set. The * symbol can be used to represent all of the fields

SQL-DML SELECT Format: SELECT column_name(s) FROM table_name Example: SELECT LastName, FirstName, Address FROM Students; To select specified columns, the SELECT command is followed by a comma separated list of fields to be selected from the table

SQL-DML SELECT SELECT DISTINC: this keyword is used to return only distinct (unique) values from the table. If there are multiple values of a specified field, the distinct result-set will display only one. Format: SELECT DISTINCT column_name(s) FROM table_name Example: SELECT DISTINCT ShipName FROM Orders;

SQL-DML SELECT LIMIT(X): this keyword specifies the number of rows to be returned from the beginning of the result-set. X specifies the rows returned Format: SELECT column_name(s) FROM table_name LIMIT X; Example: SELECT ShipName FROM Orders LIMIT 10;

SQL-DML SELECT WHERE Clause: It is used to select a field when a certain criteria set of conditions are desired The WHERE Clause is optional To create the conditions (called selection criteria) SQL provides a set of operators to further qualify what criteria should be specified

SQL-DML Where Operators OperatorDescriptionExample =Equal toWHERE country = ‘ireland’ <>, !=Not equal toWHERE country != ‘USA’ >Greater thanWHERE salary > <Less thanWHERE age < 35 >=, <=Greater/Less Than or EqualWHERE cost >=1200 IS [NOT] NULLIs NULL (vo value) or Not NULLWHERE birth = NULL BETWEENBetween an inclusive rangeWHERE last_name BETWEEN ‘Doherty’ AND ‘McDAID’ LIKESearch for a value like a patternWHERE name LIKE ‘D%’ NOT LIKESearch for a value not like a patternWHERE country NOT LIKE ‘Sw%’ !, NOTLogical not for negationWHERE age ! 10; ||, ORLogical ORWHERE order_number > 10 || part_number = 80 &&, ANDLogical ANDWHERE age>12 && age < 21 XORExclusive ORWHERE status XOR

SQL-DML Using Quotes: Quotes are always an issue in programming languages. (single quotes?, double quotes?, when?) SQL uses single quotes around text values (MySQL also accepts double quotes) Numeric Values should not be enclosed in quotes.

SQL-DML Comparing Strings: When comparing strings using =, the string must be exactly as typed for the condition to be true – this include length and type of characters. NULL: Null means that there is not a value in the field, or it is unknown, but does not mean a value of zero.

DML-SQL LIKE – NOT LIKE: The pattern matching operator can be used as a condition in the WHERE clause, allowing the selection of rows that are ‘like’ or match a pattern A percent sign (%) can be used as a wildcard to match any possible character that might appear before and/or after the character(s) specified. A _ is used to match a single character. The LIKE/NOT LIKE condition can be used in any valid SQL statement, including SELECT, INSERT, UPDATE or DELETE.

DML-SQL Examples of the wildcard % uses: SELECT CompanyName, Country FROM Customers WHERE country LIKE ‘SW%’; – Returns all the customers and countries in which the country starts with “Sw” i.e. Sweden, Switzerland SELECT City, Country FROM suppliers WHERE City LIKE ‘%o’; – Returns all cities and countries where the % matches any city that ends with a letter o. SELECT CompanyName FROM customers WHERE CompanyName LIKE ‘%Super%’ – Returns all company names where the % matches any company name that contains the pattern “Super”

DML-SQL Examples of the wildcard _ uses: SELECT Extension, Firstname FROM Employees WHERE extension LIKE ‘4_ _’; – Returns all extensions and first names where the exetension has three characters and the first character is a 4.

DML-SQL ORDER BY: Used to sort the output of a query in either ascending (ASC, the default) or descending (DESC) order where the values being sorted are either strings or numbers Format: SELECT column_name(s) FROM table_name [WHERE condition] ORDER BY column [ASC, DESC] Example: SELECT Company,Ordernumber FROM Orders ORDER BY Company;

SQL-DML INSERT The INSERT statement is used ot insert new rows into a table. After the VALUES keyword, a comma- separated list of column names follows Format: INSERT INTO table_name VALUES (value1, value2, … ) INSERT INTO table_name (column1, column2,…) VALUES (value1, value2, … ) Example: INSERT INTO Shippers (CompanyName, Phone) VALUES (‘FEDEX’,’ ’);

SQL-DML INSERT Usually, the tables have a primary key column that is usually set to auto-increment; when this is the case, the id of the table is created by the database engine automatically Letting the database increment the PRIMARY KEY ensures that the value is always unique.

SQL-DML UPDATE The UPDATE statement is used to modify data in a table. The UPDATE command is followed by the name of the table where the data will be changed, followed by the SET statement to inidcate what field will be changed, and then the new value that will be assigned to the field The WHERE clause further qualifies what data is to be modified, thereby limiting the scope of the UPDATE

SQL-DML UPDATE Format: UPDATE table_name SET column_name = new value WHERE column_name = some_value; Example: UPDATE orders SET ShipCountry=‘Spain’ WHERE CustomerId = ‘whitc’;

SQL-DML DELETE The DELETE statement is used to delete rows in a table and returns the number of rows that were deleted. DELETE uses the FROM clause to specify the name of the table that contains the data you want to delete The WHERE clause specifies the criteria to identify what data should be removed. BE CAREFUL: Without the WHERE clause ALL ROWS are DELETED

SQL-DML DELETE If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted. Format: DELETE FROM table_name WHERE column_name = some_value; Example: DELETE FROM orders WHERE ShipCountry = ‘Greenland’;

PHPMyAdmin Tutorial LIVE

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,c scan,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

Go ahead and create the database and table using PHPMyAdmin or MySQL command Prompt

Data capture form Patient Name: Appointment type General Practicioner Specialist Surgery link to php script file use get to check form is working correct post could also be used, user choice table name 3 options for app type

Radio button 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 button

PHP-process.php <?php $id = $_GET['patid']; $name = $_GET['name']; $app = $_GET['appointment']; $ward = $_GET['ward']; $string 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

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

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

Database 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

INSERT data $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 my-sql error causes Query to insert all data from html form + date obtained from previous query

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

Table design for results 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 are the fields in the database

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

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

Deleting Records HTML Button to call delete statements: Query to Delete Data from the Database: Patient ID: <?php $patid=$_REQUEST['patid']; $query = "DELETE from discharge WHERE patid=$patid"; $result = mysql_query($query,$link) or die(mysql_error()); $affected = mysql_affected_rows($link); if ($affected >0) {echo "success";} else {echo "fail";} ?> Obtaining patid from form User Feedback Remember to add the connection lines using $link to connect to the db

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 57