Академический Документы
Профессиональный Документы
Культура Документы
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.
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.
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>"; ?>
<?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.
<?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"; ?>
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>
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.
} //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.'); }
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.
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:
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>
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>
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:
<b>Sub-Page Title</b><p>
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.
<?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:
<?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.
<?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).
<?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 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'); $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
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:
?>
</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>";
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.