Chapter 4-2 PHP Part 2
Chapter 4-2 PHP Part 2
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.
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
Create Table
To create 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.
Fields name
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); ?>
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
<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 (trim($id)=="" || trim($name)=="" || trim($un)=="" || trim($ps)=="" || trim($cps)=="" || trim($age)=="" || trim($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);?>
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>"; echo "<form method='post' action='e3_edit.php'>"; while ($row = mysql_fetch_array($result)) { 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>"; } echo </form></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 (trim($name)=="" || trim($un)=="" || trim($ps)=="" || trim($age)=="" || trim($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); ?>
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); ?>
Useful Functions:
mysql_num_rows() md5() mysql_fetch_object() and reading data as object mysql_insert_id()
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.
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. 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.
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"]; } }
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