ITCS373: Internet Technology Server-Side Programming PHP – Part 2 Dr. Faisal Al-Qaed.

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

PHP SQL. Connection code:- mysql_connect("server", "username", "password"); Connect to the Database Server with the authorised user and password. Eg $connect.
PHP File Upload ISYS 475.
1 Chapter 5 – Handling HTML Controls in Web Pages spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
XAMPP: Cross – Apache, MySQL, Php, Perl + FileZilla, Tomcat NetBeans: IDE PHP Installation.
Performed by:Gidi Getter Svetlana Klinovsky Supervised by:Viktor Kulikov 08/03/2009.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
Uploading Files. Why? By giving a user the option to upload a file you are creating an interactive page You can enable users have a greater web experience.
U NIT 4 F ILE U PLOAD. I. C REATE AN U PLOAD -F ILE F ORM - With PHP, it is possible to upload files to the server.To allow users to upload files from.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
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.
Deleting and Updating Records in MySQL using PHP Basharat Mahmood, Department of Computer Science,CIIT,Islamabad, Pakistan. 1.
© 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.
INTERNET APPLICATION DEVELOPMENT For More visit:
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.
INTERNET APPLICATION DEVELOPMENT For More visit:
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.
PHP Advance. Agenda Server side Includes File Handling Cookies Sessions Error/Exception handling Database handling with MySQL sending.
COLD FUSION Deepak Sethi. What is it…. Cold fusion is a complete web application server mainly used for developing e-business applications. It allows.
PHP meets MySQL.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
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.
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.
MySQL Databases & PHP Integration Using PHP to write data to, and retrieve data from, a MySQL database.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
INTERNET APPLICATION DEVELOPMENT Practical on Sessions.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
ITCS373: Internet Technology Lecture 5: More HTML.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Creating databases for web applications Library. New example: student database. Homework: Complete class example. Catch up on source postings. Do creation.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
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.
CST336, Spring 2015 Week 8: PHP File Upload. PHP provides specific functions to handle binary data such as uploading a file into the server, storing it.
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)
Chapter 7: Pratical Example – Implementation of Web File Sharer.
MySQL. Is a SQL (Structured Query Language) database server. Can be accessed using PHP with embedded SQL Queries Supports Large DB’s, 60,000 tables with.
LECTURE 3 MYSQL Database. PHP MYSQL CONNECTION MySQL is a database system used on the web MySQL is a database system that runs on a server MySQL is ideal.
CHAPTER 10 PHP MySQL Database
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
CSC 405: Web Application Engineering II8.1 Web programming using PHP What have we learnt? What have we learnt? Underlying technologies of database supported.
MySQL MySQL and PHP – interacting with a database.
PHP Form Processing * referenced from
Unit 7 How to Upload Files. A very useful aspect of PHP is its ability to manage file uploads to your server. Before you can use PHP to manage your uploads,
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
PHP File Handling. Opening a file Fopen(filename,mode) Closing a file Fclose(filename)
 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.
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Introduction to Web programming
BASIC PHP and MYSQL Edward S. Flores.
PHP Overview PHP: Hypertext Preprocessor Server-Side Scripting
Handling Files In particular, uploading files.
Lecture 2 - SQL Injection
Tutorial 6 PHP & MySQL Li Xu
Handling Files In particular, uploading files.
Introduction to Web programming
Presentation transcript:

ITCS373: Internet Technology Server-Side Programming PHP – Part 2 Dr. Faisal Al-Qaed

PHP and MySQL DB MySQL is a database server MySQL is ideal for both small and large applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform) PHPMyAdmin: it is a web-based tool that allow you to administrate your MySQL databases over the WWW, built using a set of PHP Scripts.

MySQL DataBase MySQL is a database. A database is integrated collection of data. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders". A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. A databse query is a question or a request. With MySQL, we can query a database (using Structured Query Language (SQL)) for specific information and have a recordset returned.

Assume we have Customer Table

A quick SQL Tutorial To retrieve data from the table, we use select * from tablename: Select * from Customer Select ID, Name, Age from Customer Select * from Customer where ID=1 Select * from Customer where Age <=20 Select Occupation from Customer where Name Like ‘F%’ //what about ‘%e%’ Select * from Customer where Name Like ‘F_r[ei]’ //what about ‘[ab]_[!ei]%’ Select * from Customer order by ID DESC Select * from Customer where Occupation=‘Student’ order by Name, Age SELECT * FROM Customer WHERE Name=‘Hesham' AND Age<>34 (try OR)

SQL Insert INSERT INTO table_name VALUES (value1, value2, value3,...) INSERT INTO Customer VALUES (1,'Nilsen', ‘NN', ‘abc123', 22, ‘Student')

SQL Update UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value UPDATE Customer SET Age=37, Occupation='Student' WHERE Name=‘Noor' OR ID=2

SQL Delete DELETE FROM table_name WHERE some_column=some_value DELETE FROM Customer WHERE Name=‘Hesham' AND Age>30

Type in: localhost Click on phpMyAdmin to access MySQL Enter your username and password (i.e. root and abc123)

First Step: Create DB Enter DB Name and click create

Create Table To create table To add more fields to the table

Insert Data Select the table students, click on insert, then type in the values, then finally click on go button to insert new data into your table

Browse/Edit/Delete After inserting data, you can browse the table by clicking Browse (see Top-Left), and then you will see you table, clicking on pencil picture will allow you to edit that row, or clicking on the X picture will allow you to delete that record.

Using SQL You can use SQL statements to Create Table, Insert records, browse records using Select, Delete records, etc. Enter your SQL here Execute your SQL Fields name

Allow you to export DB and import it to different machine Allow you to edit and delete database

In the LAB you were given a quick tutorial on using MySQL with PHPMyAdmin and SQL statements. You should now know:  How to create/delete a database?  How to create/delete table?  How to insert/edit/delete a record?  How to browse table contents?  How to use SQL to create table, select/update/delete/insert records?  How to import/export your database?

MySQL database Connect <?php $dbh=mysql_connect("localhost", “root", “abc123") or die ('I cannot connect to the database because: '. mysql_error()); mysql_select_db ("itcs373"); //do something here echo "Display this text"; //Close Connection mysql_close($dbh); ?>

Displaying the data in the table Select $result = mysql_query("SELECT * FROM Customer"); Display in a table echo " ID Name Age "; while($row = mysql_fetch_array($result)) { echo " "; echo " ". $row[‘ID']. " "; echo " ". $row[‘Name']. " "; echo " ". $row[‘Age']. " "; echo " "; } echo " ";

Inserting into the table mysql_query("INSERT INTO Customer VALUES(10,‘Ali',’un’, '23‘,25,’Student’ )") or die(mysql_error());

More Examples $result = mysql_query("SELECT * FROM Customer WHERE Age>'18' " ); $result = mysql_query("SELECT * FROM Customer WHERE Age>'18' ORDER By Name" ); mysql_query("UPDATE Customer SET Age = '36‘ WHERE Name = ‘Ali' ") or die(mysql_error()); mysql_query("DELETE FROM Customer WHERE id='2'") or die(mysql_error());

Examples Create a database named “example” Create a table named “customers” with the following attributes: ID – type= int Name – type= varchar of size 20 Username – type= varchar of size 20 Password – type= varchar of size 20 Age – type= int Occupation – type= varchar of size 30

Example 1: Login Verification Querying a MySQL Database Username Password

e1_select.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (‘Error'. mysql_error()); mysql_select_db ("example"); extract($_POST); $result = mysql_query("SELECT * FROM customers WHERE Username='$un'"); echo " "; if ($row = mysql_fetch_array($result)) { if ($row['Password']==$ps) {echo "Successful Login"; echo " ID Name Age Occupation "; echo " ". $row['ID']. " ". $row['Name']. " ". $row['Age']. " "; echo " ". $row['Occupation']. " "; } else echo "Invalid Password"; } else echo "Invalid Username "; echo " "; mysql_close($dbh);?>

Example 2: User Sign-Up

Form.htm ID: Name: Age: Username: Password Confirm Password: Occupation: Student Manager Messenger Teacher

e2_insert.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (mysql_error()); mysql_select_db ("example"); extract($_POST); if ($id=="" || $name=="" || $un=="" || $ps=="" || $cps=="" || $age=="" || $occ=="") echo ("Missing information"); else if ($ps!=$cps) echo ("Password and Confirm Password are not identical"); else { mysql_query("INSERT INTO Customers VALUES($id,'$name','$un', '$ps',$age,'$occ')") or die (mysql_error()); echo " User was successfully registered "; } mysql_close($dbh);?>

Example 3: Update Details Read only

View.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (mysql_error()); mysql_select_db ("example"); $result = mysql_query("SELECT * FROM customers"); echo " "; echo " ID Name Age Username Password Occupation "; while ($row = mysql_fetch_array($result)) { echo " "; echo " "; echo " ". $row['Name']. " "; echo " ". $row['Age']. " "; echo " ". $row['Username']. " "; echo " ". $row['Password']. " "; echo " ". $row['Occupation']. " "; } echo " "; mysql_close($dbh); ?>

e3_edit.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (mysql_error()); mysql_select_db ("example"); extract($_POST); $result = mysql_query("SELECT * FROM customers WHERE ID=$ID"); if ($row = mysql_fetch_array($result)) { echo " "; echo "ID: "; echo "Name: "; echo "Age: "; echo "Username: "; echo "Password: "; echo "Occupation: "; echo " "; } mysql_close($dbh);?>

e3_update.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (mysql_error()); mysql_select_db ("example"); extract($_POST); if ($id=="" || $name=="" || $un=="" || $ps=="" || $age=="" || $occ=="") echo ("Missing information"); else { $mySql="UPDATE Customers SET Name='$name', Username='$un', Password='$ps', Age=$age, Occupation='$occ' WHERE ID=$id"; mysql_query($mySql) or die (mysql_error()); echo " User info was successfully updated "; } mysql_close($dbh); ?>

Example 4: Delete Users Note: use the same code as view.php for listing all users but change the form action to ‘e4_delete’

e4_delete.php <?php require("noCache.php"); $dbh=mysql_connect("localhost", "root", "abc123") or die (mysql_error()); mysql_select_db ("example"); extract($_POST); $mySql="DELETE FROM Customers WHERE ID=$ID"; mysql_query($mySql) or die (mysql_error()); echo " User info was deleted successfully "; mysql_close($dbh); ?>

PHP Upload A very useful aspect of PHP is its ability to manage file uploads to your server. However, allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

HTML Form needed for upload Choose a file to upload:

Here is a brief description of the important parts of the above code: enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly. action="uploader.php" - The name of our PHP page that will be created, shortly. method="POST" - Informs the browser that we want to send information to the server using POST. input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example. input name=“myFile" - myFile is how we will access the file in our PHP script.

When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.associative array The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.  myFile - is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.  $_FILES[‘myFile']['name'] - name contains the original path of the user uploaded file.  $_FILES[‘myFile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

Simple File Upload Example <?php $target_path = "uploads/"; // Add the original filename to our target path. Result is "uploads/filename.extension" $target_path = $target_path.basename($_FILES[‘myFile']['name']); If (move_uploaded_file($_FILES[' myFile']['tmp_name'], $target_path)) { echo "The file ".basename( $_FILES[' myFile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Note: You will need to create a new directory in the directory where uploader.php resides, called "uploads", as we are going to be saving files there.

PHP - File Upload: Safe Practices! Note: This script is for education purposes only. We do not recommend placing this on a web page viewable to the public. These few lines of code we have given you will allow anyone to upload data to your server. Because of this, we recommend that you do not have such a simple file uploader available to the general public. Otherwise, you might find that your server is filled with junk or that your server's security has been compromised.

Practical Upload Example Filename:

upload_file.php <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; echo "Temp file: ". $_FILES["file"]["tmp_name"]. " "; if (file_exists("upload/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/". $_FILES["file"]["name"]); echo "Stored in: ". "upload/". $_FILES["file"]["name"]; } } else { echo "Invalid file"; } ?>

List of Mime Types Pdf = application/pdf Doc = application/msword Css = text/css Bmp = image/bmp Htm/html = text/html Mov = video/quicktime Mp3 = audio/mpeg3 Mpg = video/mpeg Ppt = application/powerpoint Txt = text/plain For Complete Reference: check this website

PHP what else? You can still do many many more things with PHP and SS scripts:  You can create/manage/delete/rename directories/files on the server (i.e. mkdir($dirName,0777);)  You can access and manipulate XML data easily.  You can interact with networking applications such as DNS, mail server, ftp, open network sockets etc.  PHP also has a great number of functions that will secure sensitive website data (i.e. encryptions, hash functions, etc.)  PHP regular expression is useful for complex data validation