Вы находитесь на странице: 1из 17

Upload a File and write to MySQL

By Angela Bradley, About.com Guide

Create a Database
On our site, we have tutorials about adding data to a MySQL database, and tutorials about uploading files, but recently one of our forum users asked: "I know how to submit data into a mySQL table through a form. Now I want to upload the image file to the remote directory (say, 'images/') but at the same time save the file-name in the table. " This is a very common question because it has a lot of uses. Often you want a user to be able to upload a photo, but you don't want to bog down your database space by saving all the images directly into the database. You instead save the image to your server, but keep a record in the database of what file was saved so you can easily reference the image when needed. First let's create a database:

CREATE TABLE employees (name VARCHAR(30), email VARCHAR(30), phone VARCHAR(30), photo VARCHAR(30))
This SQL code creates a database called 'employees' that can hold their name, email, phone and the name of their photo.

Creating a Form
<form enctype="multipart/form-data" action="add.php" method="POST"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name = "email"><br> Phone: <input type="text" name = "phone"><br> Photo: <input type="file" name="photo"><br> <input type="submit" value="Add"> </form>
This is simply an HTML form that you would use to collect information to be added to the database. We could add more fields if we wanted, but then we would also need to add the appropriate fields to our MySQL database.

Processing the Data


<?php //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $pic=($_FILES['photo']['name']); // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ; mysql_select_db("Database_Name") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?>
This code should be saved as add.php. To understand what each step of this script is doing it is best to read the comments within the code. Basically it gathers the information from the form and

then writes it to the MySQL database. Once that is done, it saves the file to the /images directory (relative to the script) on your server. If you are only allowing photo uploads, you might consider limiting the allowed file types to jpg, gif and png. We also don't check if the file already exists, so if two people both upload a file called MyPic.gif, one will overwrite the other. A simple way to remedy this would be to simply rename each file with a unique ID.

Viewing Your Data


<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ; mysql_select_db("Database_Name") or die(mysql_error()) ; //Retrieves data from MySQL $data = mysql_query("SELECT * FROM employees") or die(mysql_error()); //Puts it into an array while($info = mysql_fetch_array( $data )) { //Outputs the image and other data Echo "<img src=http://www.yoursite.com/images/".$info['photo'] ."> <br>"; Echo "<b>Name:</b> ".$info['name'] . "<br> "; Echo "<b>Email:</b> ".$info['email'] . " <br>"; Echo "<b>Phone:</b> ".$info['phone'] . " <hr>"; } ?>
This script very simply queries the database and retrieves all of the information in it. It then echos each back until it has shown all the data. To show the image, we just use normal HTML for the image, and only change the last part (the actual image name) with the image name stored in our database. For more information on retrieving information from the database, read this tutorial.

PHP MySQL Tutorial


By Angela Bradley, About.com Guide

Connect to MySQL
Interacting with MySQL makes PHP a far more powerful tool. In this tutorial we will go through some of the most common ways PHP interacts with MySQL. To follow along with what we are doing, you will need to create a database table by executing this command:

CREATE TABLE friends (name VARCHAR(30), fav_color VARCHAR(30), fav_food VARCHAR(30), pet VARCHAR(30)); INSERT INTO friends VALUES ( "Rose", "Pink", "Tacos", "Cat" ), ( "Bradley", "Blue", "Potatoes", "Frog" ), ( "Marie", "Black", "Popcorn", "Dog" ), ( "Ann", "Orange", "Soup", "Cat" )
This will create a table for us to work with, that has friends' names, favorite colors, favorite foods, and pets. The first thing we need to do in our PHP file is connect to the database. We do that using this code:

<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); ?>
Of course you will replace server, username, password, and Database_Name with the information relevant to your site. If you are unsure what these values are, contact your hosting provider.

Retrieve Data
Next we will retrieve the information from the database table we created called "friends"

// Collects data from "friends" table $data = mysql_query("SELECT * FROM friends") or die(mysql_error());
And we will then temporally put this information into an array to use:

// puts the "friends" info into the $info array $info = mysql_fetch_array( $data );
Now let's print out the data to see if it worked:

// Print out the contents of the entry Print "<b>Name:</b> ".$info['name'] . " "; Print "<b>Pet:</b> ".$info['pet'] . " <br>";
However this will only give us the first entry in our database. In order to retrieve all the information, we need to make this a loop. Here is an example:

while($info = mysql_fetch_array( $data )) { Print "<b>Name:</b> ".$info['name'] . " "; Print "<b>Pet:</b> ".$info['pet'] . " <br>"; }
So let's put all the these ideas together to create a nicely formatted table with this final php code:

<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); $data = mysql_query("SELECT * FROM friends") or die(mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>Name:</th> <td>".$info['name'] . "</td> "; Print "<th>Pet:</th> <td>".$info['pet'] . " </td></tr>"; } Print "</table>"; ?>

SQL Queries with PHP


Now that you have done one query, you can do more complicated queries using the same basic syntax. If you have forgotten the queries, you can review them in the MySQL glossary. Let's try to do a query of our database for people who have cats for a pet. We will do this by adding a WHERE clause to set pet equal to Cat.

<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); $data = mysql_query("SELECT * FROM friends WHERE

pet='Cat'") or die(mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>Name:</th> <td>".$info['name'] . "</td> "; Print "<th>Color:</th> <td>".$info['fav_color'] . "</td> "; Print "<th>Food:</th> <td>".$info['fav_food'] . "</td> "; Print "<th>Pet:</th> <td>".$info['pet'] . " </td></tr>"; } Print "</table>"; ?>

Create Tables
Following this same structure, we can connect to a database and create new tables. At the end we will print a line, so we know that it is done executing:

<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); mysql_query("CREATE TABLE tablename ( name VARCHAR(30), age INT, car VARCHAR(30))"); Print "Your table has been created"; ?>
I find this method is often used when installing a PHP program someone else has written. Often an install file includes a way for the user to update the MySQL database from the browser. This allows people less familiar with the code to install the program more easily.

Insert Into Tables


We can use the same method of using SQL commands to populate our database as we did to create it. Here is an example:

<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); mysql_query("INSERT INTO tablename VALUES ( 'Bill', 29, 'Ford' ), ( 'Mike', 16, 'Beetle' ), ( 'Alisa', 36, 'Van' )"); Print "Your table has been populated"; ?>

PHP Login Script


By Angela Bradley, About.com Guide

Registration Page 1
<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //This code runs if the form has been submitted

if (isset($_POST['submit'])) { //This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { die('You did not complete all of the required fields'); } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { die('Sorry, the username '.$_POST['username'].' is already in use.'); } // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { die('Your passwords did not match. '); } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } // now we insert it into the database $insert = "INSERT INTO users (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); ?> <h1>Registered</h1> <p>Thank you, you have registered - you may now login</a>.</p>

Script continued and explained on the next page.

Registration Page 2
<?php } else { ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table border="0"> <tr><td>Username:</td><td> <input type="text" name="username" maxlength="60"> </td></tr> <tr><td>Password:</td><td> <input type="password" name="pass" maxlength="10"> </td></tr>

<tr><td>Confirm Password:</td><td> <input type="password" name="pass2" maxlength="10"> </td></tr> <tr><th colspan=2><input type="submit" name="submit" value="Register"></th></tr> </table> </form> <?php } ?>
Registration Full Code Basically what this does is check to see if the form has been submitted. If it has been submitted it checks to make sure that the data is all OK (passwords match, username isn't in use) as documented in the code. If everything is OK it adds the user to the database, if not it returns the appropriate error. If the form has not been submitted, they are shown the registration form, which collects the username and password.

The Login Page 1


<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])) //if there is, it logs you in and directes you to the members page { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else { header("Location: members.php"); } }

} //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted // makes sure they filled it in if(!$_POST['username'] | !$_POST['pass']) { die('You did not fill in a required field.'); } // checks it against the database if (!get_magic_quotes_gpc()) { $_POST['email'] = addslashes($_POST['email']); } $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['password'] = stripslashes($info['password']); $_POST['pass'] = md5($_POST['pass']); //gives error if the password is wrong if ($_POST['pass'] != $info['password']) { die('Incorrect password, please try again.'); }

Script continued and explained on the next page.

The Login Page 2


else { // if login is ok then we add a cookie $_POST['username'] = stripslashes($_POST['username']); $hour = time() + 3600; setcookie(ID_my_site, $_POST['username'], $hour); setcookie(Key_my_site, $_POST['pass'], $hour); //then redirect them to the members area header("Location: members.php"); } } } else { // if they are not logged in ?> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <table border="0"> <tr><td colspan=2><h1>Login</h1></td></tr> <tr><td>Username:</td><td> <input type="text" name="username" maxlength="40"> </td></tr> <tr><td>Password:</td><td> <input type="password" name="pass" maxlength="50"> </td></tr> <tr><td colspan="2" align="right"> <input type="submit" name="submit" value="Login"> </td></tr> </table> </form> <?php } ?>

Login Full Code This script first checks to see if the login information is contained in a cookie on the users computer. If it is, it tries to log them in. If this is successful they are redirected to the members area. If there is no cookie, it allows them to login. If the form has been submitted, it checks it against the database and if it was successful sets a cookie and takes them to the members area. If it has not been submitted, it shows them the login form.

Members Area
<?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //checks cookies to make sure they are logged in if(isset($_COOKIE['ID_my_site'])) { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { //if the cookie has the wrong password, they are taken to the login page if ($pass != $info['password']) { header("Location: login.php"); } //otherwise they are shown the admin area else { echo "Admin Area<p>"; echo "Your Content<p>"; echo "<a href=logout.php>Logout</a>"; } } } else //if the cookie does not exist, they are taken to the login screen { header("Location: login.php"); } ?>

This code checks our cookies to make sure the user is logged in, the same way the login page did. If they are logged in, they are shown the members area. If they are not logged in they are redirected to the login page.

Logout Page

<?php $past = time() - 100; //this makes the time in the past to destroy the cookie setcookie(ID_my_site, gone, $past); setcookie(Key_my_site, gone, $past); header("Location: login.php"); ?>
All our logout page does is destroy the cookie, and then direct them back to the login page. We destroy the cookie by setting the expiration to some time in the past.

Use PHP in a File That Supports Mixed Scripting Languages


How to use PHP in a mixed scripting language file
By Angela Bradley, About.com Guide

You already know how to start and finish a PHP file using regular methods. The code below shows the common way of creating a PHP file:

<?php echo "Hello About.com!"; ?>


What you might not know is that you can run this same bit of code using the script tag:

<script language = "php"> echo "Hello About.com!"; </script>


The script tags can identify a language (PHP or otherwise) who's code you will be running in a section. This is useful in a file that allows for mixed scripting languages. While it is not a common setup, it is sometimes used. By using the script tags, you can easily identify what language is where, and when it switches.

How To Template Your Site


By Angela Bradley, About.com Guide

When every page of your website follows the same design theme, it is often easiest to create a template for the site. The specific pages of the site only hold their content and not their design.

This makes design changes easy, as they take place on all the pages at once, and there is no need to individually update specific pages. 1. The first thing you need to do is create a file called header.php. In this file you will hold all of your page design that comes before your content. Here is an example:

2. <html>

3. <head><title>My Site</title></head>

4. <body>

5. <h2>My Site Title</h2><p>

6. My Site menu goes here........... Choice 1 Choice 3

Choice 2

<hr>
1. Next we need to make a file called footer.php. This file will contain all of the site design information that goes below the content. Here is an example:

2. <hr>

3. <small>Copyright 2008 My Site</small><br>

4. </body>

5. </html>
6. Finally you need to create the content pages for your site. In this file you will: 1. Call the header file 2. Put in the page specific content 3. Call the footer file Here is an example of how:

<?php include 'header.php'; ?>

<b>Sub-Page Title</b><p>

Here is the specific content of this page....<br>

<?php include 'footer.php'; ?>

Tips: 1. Remember to save all your files with the .php extension. 2. You can have more than a header and a footer, if needed create other files to include in the middle and call them the same way! 3. Couple this with the use of a style sheet to change style within the page exclusive content easily as well.

Including External Files in PHP


By Angela Bradley, About.com Guide

Include and Require


PHP is capable of utilizing SSI to include an external file into the file being executed. Two commands that do this are INCLUDE () and REQUIRE (). The difference between them is that when placed within a false conditional statement, the INCLUDE is not pulled but the REQUIRE is pulled and ignored. This means that in a conditional statement it can be faster to use INCLUDE. These commands are phrased as such:

INCLUDE 'http://www.yoursite.com/path/to/file.php' ; //or REQUIRE 'http://www.yoursite.com/path/to/file.php' ;


Some of the most common uses for these commands include holding variables that are used across multiple files or holding headers and footers. If an entire site's layout is housed in external files called with SSI, any changes to site design need only be made to these files and the entire site will change accordingly.

Pulling The File


First let's create a file that will hold our variables. Let's call it variables.php

<?php //variables.php $name = 'Loretta'; $age = '27'; ?>


Now we will include this file into our second file called report.php

<?php //report.php include 'variables.php'; // or you can use the full path; include 'http://www.yoursite.com/folder/folder2/variables.php'; print $name . " is my name and I am " . $age . " years old."; ?>
As you can see, the print command easily uses these variables. You can also call the include within a function but we must declare the variables to be GLOBAL if we want to use them outside the function:

<?php function printname () { global $name; include 'variables.php'; print $name . " is my name and I am " . $age . " years old."; } printname (); print "<br>"; //The line below will work because $name is GLOBAL print "I like my name, " . $name; print "<br>"; //The next line will NOT work because $age is NOT defined as global print "I like being " . $age . " years old."; ?>

More SSI
The same commands can be used to include non PHP files such as .html files or .txt files. First let's make our variables.php file into variables.txt and see what happens when we try to call it:

<?php //variables.txt $name = 'Loretta'; $age = '27'; ?> <?php //report.php include 'variables.txt'; // or you can use the full path; include 'http://www.yoursite.com/folder/folder2/variables.txt'; print $name . " is my name and I am " . $age . " years old."; ?>
This works just fine. Basically the server replaces your include ''; line with the code from the file, so it actually processes this:

<?php //report.php //variables.txt $name = 'Loretta'; $age = '27'; // or you can use the full path; include 'http://www.yoursite.com/folder/folder2/variables.txt print $name . " is my name and I am " . $age . " years old."; ?>
It is important to note that even if you are including a non.php file, if your includes contain PHP code you must have the <?php ?> tags or it will not be processed as PHP. For example, our variables.txt file above included PHP tags. Try saving the file again without them and then run report.php:

//variables.txt $name = 'Loretta'; $age = '27';


As you can see this does not work. Since you need the <?php ?> tags anyway, and any code in a .txt file can be viewed from a browser (.php code can not,) I would suggest just naming your files with the .php extension to begin with.

Read & Return Data From Files Into PHP


By Angela Bradley, About.com Guide

Reading File Data


If you have written data to a file from PHP, or you have a file on your server you need to read with PHP, there are quite a few ways you can do it. The four ways we will cover here are fread (), fgets (), file (), and file_get_contents(). The one you choose is based upon your needs, and how the data in the file you are accessing is formatted.

Using fread () in PHP


You can use fread () when you want to read the file data and return it to a string. You can specify how many bytes to read, but 8192 is the maximum. If you choose to use this method, you must be sure to open the file first.

<?php $YourFile = "YourFile.txt"; $handle = fopen($YourFile, 'r'); $Data = fread($handle, 512); fclose($handle); print $Data; ?>
This code opens the file YourFile.txt from your server and puts it's entire contents into the variable $Data as a string. We then print $Data, so the script is basically outputting the file contents onto a page.

Using file_get_contents () in PHP


File_get_contents () is similar to fread () in that it returns the entire contents of the file to a single string, however it can be done in a single line and performs better then fread ().

<?php $file = file_get_contents ('YourFile.txt'); Echo $file; ?>


This little bit of code retrieves the data from YourFile.text and then echos it onto the page.

Using fgets () in PHP


Fgets () is used to read the data from a file one line at a time starting from the pointer. It defaults to only reading the first 1024 bytes of a line, however you can set this variable higher or lower if you wish. If your file is not separated with line breaks, this is not the right function to use.

<?php $YourFile = "YourFile.txt"; $handle = fopen($YourFile, 'r'); while (!feof($handle)) { $Data = fgets($handle, 256); print $Data; print "<p>"; } fclose($handle); ?>
What this code does first is open the file YourFile.txt. It then enters into a loop that will read up to 256 bytes of the file line, print the contents of the line, print an HTML paragraph break, and then repeat this with the next line until it reaches the end of the file (foef).

Using file () in PHP


File () is similar to fgets in that it reads the data one line at a time, however it returns it all at once into an array. The array contains the line number, and the data corresponding to each line number starting with 0. If you want to do more than simply echo the data, having it in an array will provide much more flexibility making file () more useful than fgets ().

<?php $lines = file('YourFile.txt'); foreach ($lines as $line_num => $line) { print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n"; } ?>
What this code does first is put the contents of YourFile.txt into the array called $lines. It then enters into a loop which prints each line number in red, followed by the line contents, and repeats until all lines have been printed.

Write to a file from PHP


By Angela Bradley, About.com Guide

Write To A File
From PHP you are able to open up a file on your server and write to it. If the file does not exist we can create it, however if the file already exists you must chmod it to 777 so it will be writable. When writing to a file, the first thing you need to do is to open up the file. We do that with this code:

<?php $File = "YourFile.txt"; $Handle = fopen($File, 'w'); ?>


Now we can use the fwrite command to add data to our file. We would do this as shown below:

<?php $File = "YourFile.txt"; $Handle = fopen($File, 'w'); $Data = "Jane Doe\n"; fwrite($Handle, $Data); $Data = "Bilbo Jones\n"; fwrite($Handle, $Data); print "Data Written"; fclose($Handle); ?>
At the end of the file we use fclose to close the file we have been working with. You may also notice we are using \n at the end of our data strings. The \n servers as a line break, like hitting the enter or return key on your keyboard. You now have a file called YourFile.txt that contains the data: Jane Doe Bilbo Jones

Rewrite Data
If we were to run this very same thing again only using different data, it would erase all of our current data, and replace it with the new data. Here is an example:

<?php $File = "YourFile.txt"; $Handle = fopen($File, 'w'); $Data = "John Henry\n"; fwrite($Handle, $Data); $Data = "Abigail Yearwood\n"; fwrite($Handle, $Data); print "Data Written"; fclose($Handle); ?>
The file we created, YourFile.txt, now contains this data: John Henry Abigail Yearwood

Adding To Data
Let's say that we don't want to rewrite over all of our data. Instead we just want to add more names to the end of our list. We would do that by changing our $Handle line. Currently it is set to w which means write only, beginning of file. If we change this to a it will append the file. This means it will write to the end of the file. Here is an example:

<?php $File = "YourFile.txt"; $Handle = fopen($File, 'a'); $Data = "Jane Doe\n"; fwrite($Handle, $Data); $Data = "Bilbo Jones\n"; fwrite($Handle, $Data); print "Data Added"; fclose($Handle); ?>
This should add these two names to the end of the file, so our file now contains four names: John Henry Abigail Yearwood Jane Doe Bilbo Jones

PHP with HTML


Using PHP and HTML on the same page
By Angela Bradley, About.com Guide

There are two ways to use HTML on your PHP page. The first way is to put the HTML outside of your PHP tags. You can even put it in the middle if you close and reopen the <?php -and- ?> tags. Here is an example of putting the HTML outside of the tags:

<html> <title>HTML with PHP</title> <body> <h1>My Example</h1>

<?php //your php code here

?>

<b>Here is some more HTML</b>

<?php //more php code ?>

</body> </html>

As you can see you can use any HTML you want without doing anything special or extra in your .php file, as long as it is outside of the PHP tags. The second way to use HTML with PHP is by using PRINT or ECHO. By using this method you can include the HTML inside of the PHP tags. This is a nice quick method if you only have a line or so to do. Here is an example:

<?php Echo "<html>"; Echo "<title>HTML with PHP</title>"; Echo "<b>My Example</b>";

//your php code here

Print "<i>Print works too!</i>"; ?>

Using one or both of these methods you can easily embed HTML code in your PHP pages, to give them a nicer more formatted look, and make them more user friendly.

Вам также может понравиться