Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "ITCS373: Internet Technology Server-Side Programming PHP – Part 2 Dr. Faisal Al-Qaed."— Presentation transcript:

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

2 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.

3 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.

4 Assume we have Customer Table

5 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)

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

7 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

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

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

10 First Step: Create DB Enter DB Name and click create

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

12 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

13 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.

14 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

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

16 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?

17 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); ?>

18 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 " ";

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

20 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());

21 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

22 Example 1: Login Verification Querying a MySQL Database Username Password

23 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);?>

24 Example 2: User Sign-Up

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

26 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);?>

27 Example 3: Update Details Read only

28 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); ?>

29 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);?>

30 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); ?>

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

32 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); ?>

33 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.

34 HTML Form needed for upload Choose a file to upload:

35 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.

36 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.

37 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.

38 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.

39 Practical Upload Example Filename:

40 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"; } ?>

41 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 http://www.webmaster-toolkit.com/mime-types.shtml

42 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


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

Similar presentations


Ads by Google