430 likes | 589 Views
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
E N D
ITCS373: Internet TechnologyServer-Side ProgrammingPHP – 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.
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_nameVALUES (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. Execute your SQL Fields name Enter your SQL here
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 "<table border='1'> • <tr> <th>ID</th><th>Name</th><th>Age</th></tr>"; • while($row = mysql_fetch_array($result)) • { echo "<tr>"; • echo "<td>" . $row[‘ID'] . "</td>"; • echo "<td>" . $row[‘Name'] . "</td>"; • echo "<td>" . $row[‘Age'] . "</td>"; • echo "</tr>"; } • echo "</table>";
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 <html><body> <h2> Querying a MySQL Database </h2> <form method="post" action="e1_select.php"> Username <input name="un" /> <br /> Password <input type="password" name="ps" /> <br /> <input type="submit" value="Sign-in" /> </form></body></html>
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 "<html><body>"; if ($row = mysql_fetch_array($result)) { if ($row['Password']==$ps) { echo "Successful Login"; echo "<table border='1'><tr> <th>ID</th><th>Name</th><th>Age</th><th>Occupation</th></tr>"; echo "<tr><td>" . $row['ID'] . "</td><td>" . $row['Name'] . "</td><td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Occupation'] . "</td></tr>"; } else echo "Invalid Password"; } else echo "Invalid Username "; echo "</table></body></html>"; mysql_close($dbh);?>
Form.htm <html><body> <form method="post" action="e2_insert.php"><table> <tr><td>ID:</td><td><input type="text" name="id"></td></tr> <tr><td>Name:</td><td><input type="text" name="name"></td></tr> <tr><td>Age:</td><td><input type="text" name="age"></td></tr> <tr><td>Username:</td><td><input type="text" name="un"></td></tr> <tr><td>Password</td><td><input type="password" name="ps"></td></tr> <tr><td>Confirm Password:</td><td><input type="password" name="cps"></td></tr> <tr><td>Occupation:</td><td><Select name="occ"> <option value="Student">Student</option> <option value="Manager">Manager</option> <option value="Messenger">Messenger</option> <option value="Teacher">Teacher</option> </select></td> </tr></table><br /><br /><input type="submit" value="Add New"> <input type="reset" value="Cancel"> </form></body></html>
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 "<h2> User was successfully registered</h2>"; } 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 "<html><body>"; echo "<table border='1'><tr> <th>ID</th><th>Name</th><th>Age</th><th>Username</th><th>Password</th><th>Occupation</th></tr>"; while ($row = mysql_fetch_array($result)) { echo "<form method='post' action='e3_edit.php'>"; echo "<tr><td><input type='submit' name='ID' value='".$row['ID']."' /></td>"; echo "<td>" . $row['Name'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Username'] . "</td>"; echo "<td>" . $row['Password'] . "</td>"; echo "<td>" . $row['Occupation'] . "</td></tr></form>"; } echo "</table></body></html>"; 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 "<html><body>"; echo "<form method='post' action='e3_update.php'><br />"; echo "ID: <input name='id' value='".$row['ID']."' readonly/><br />"; echo "Name: <input name='name' value='".$row['Name']."' /><br />"; echo "Age: <input name='age' value='".$row['Age']."' /><br />"; echo "Username: <input name='un' value='".$row['Username']."' /><br />"; echo "Password: <input type='password' name='ps' value='".$row['Password']."' /><br />"; echo "Occupation: <input name='occ' value='".$row['Occupation']."' /><br />"; echo "<input type='submit' value='update' />"; echo "</form></body></html>"; } 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 "<h2> User info was successfully updated</h2>"; } 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 "<h2> User info was deleted successfully</h2>"; 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 <form enctype="multipart/form-data" action="uploader.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name=“myFile" type="file" /><br /> <input type="submit" value="Upload File" /> </form>
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 $_FILESassociative 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.
<?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. Simple File Upload Example
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 <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> Filename: <input type="file" name="file" /><br /> <input type="submit" name="submit" value="Submit" /> </form></body></html>
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"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; 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 http://www.webmaster-toolkit.com/mime-types.shtml
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