You are on page 1of 55

By: Jan Zumwalt

NeatInfo.com

Jan Zumwalt – neatinfo.com Pg 1 of 55 rev April 1, 2010

Table of Contents
Table of Contents........................................................................................................................... 2
PHP Syntax..................................................................................................................................... 4
Variables......................................................................................................................................... 5
Working With PHP Variables...................................................................................................................... 5
String Functions............................................................................................................................. 6
Single and Double Quotes ......................................................................................................................... 7
Concatenating............................................................................................................................................ 9
strlen() - number of characters in a string ................................................................................................... 9
str_replace() - replaces all occurrences ...................................................................................................... 9
strtoupper() – convert to upper case........................................................................................................... 9
ucfirst() – first letter to upper case .............................................................................................................. 9
trim() - remove start and end blanks ........................................................................................................... 9
If Else Statement .......................................................................................................................... 11
For Loops ..................................................................................................................................... 13
While Loops.................................................................................................................................. 14
Arrays ........................................................................................................................................... 15
Example 1 - Numeric Array – individual assignment ................................................................................. 15
Example 2 - Numeric Array – inline assignment........................................................................................ 15
Example 3 - Associative Array – (key-value pairs) .................................................................................... 15
Example 4 - Associative Array – Object (pointer) syntax........................................................................... 15
Multidimensional Arrays ........................................................................................................................... 16
Example 5 – Associative Multidimensional Arrays .................................................................................... 16
Example 6 - Pointer Multidimensional Arrays............................................................................................ 16
print_r() - Printing Arrays .......................................................................................................................... 17
Date & Time .................................................................................................................................. 18
PHP Date: strtotime() ............................................................................................................................... 18
PHP Date: mktime() ................................................................................................................................. 19
Local File IO.................................................................................................................................. 19
PHP file open modes ............................................................................................................................... 19
fgets() – Read Line .................................................................................................................................. 20
file_get_contents() - read entire file .......................................................................................................... 22
fwrite() – writing to file .............................................................................................................................. 22
Write text to a file ..................................................................................................................................... 23
Write at the beginning of a file .................................................................................................................. 23
Write at the end of a file ........................................................................................................................... 24
Write string with line breaks ..................................................................................................................... 24
Simultaneous Read / Write....................................................................................................................... 25
Remote File IO.............................................................................................................................. 27
Example 1 - open remote files.................................................................................................................. 27
Forms............................................................................................................................................ 28
Input form – visitor_form.php.................................................................................................................... 28
Process form – visitor_info.php ................................................................................................................ 28
Email ............................................................................................................................................. 29
Sending Plain Text Email ......................................................................................................................... 29
Sending HTML Email ............................................................................................................................... 29
Remote input and processing Email ......................................................................................................... 30
Sessions ....................................................................................................................................... 33
Storing information in a session ............................................................................................................... 33
Retrieving stored session information....................................................................................................... 33
Destroying/deleting session information ................................................................................................... 34
Cookies......................................................................................................................................... 35
Retrieving a cookie .................................................................................................................................. 35
Deleting a Cookie .................................................................................................................................... 36
MySql ............................................................................................................................................ 37
Setting Up The Database ......................................................................................................................... 38
Inserting Information ................................................................................................................................ 41
More Outputs........................................................................................................................................... 46
Single Records & Error Trapping.............................................................................................................. 48
Jan Zumwalt – neatinfo.com Pg 2 of 55 rev April 1, 2010

Updating & Deleting ................................................................................................................................. 51
Finishing The Script ................................................................................................................................. 54

Jan Zumwalt – neatinfo.com Pg 3 of 55 rev April 1, 2010

PHP Syntax
<html>
<title>my php page</title>
<body>
<h1>PHP Test</H1>
<?php
// Single line comment

/*
* multi-line
* comment
*/

echo "hello there!";
echo "<b>hello there!</b>";
echo "<font color='green'>hello there!</font>";
echo "today is ".date('Y-m-d');
?>
</body>
</html>

Note: At the end of each PHP statement we need need to put a semicolon, i.e. ";"
as you see in the above code. Otherwise PHP will report syntax error.

Jan Zumwalt – neatinfo.com Pg 4 of 55 rev April 1, 2010

Variables
PHP variables start with a $ sign, A variable name should only start with
underscore "_" or a letter.

A variable can only contain letters, numbers or underscore. In another words, you
can't use characters like <^# in your variables names.

<?php
$str = "I love PHP"; // variable with a string value
echo $str; // print the $str value onto the browser

$num = 100; // another variable with a integer value
echo $num; // using echo to print the $num variable

echo $str; // reuse the $str variable to print its value
echo $num; // reuse the $num variable to print its value
?>

Result: the browser should show "I Love PHP100I Love PHP100".

Working With PHP Variables

Example - PHP variable with numbers

<?php
$integer_number = 100;
echo $number;
?>

<?php
$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>

Jan Zumwalt – neatinfo.com Pg 5 of 55 rev April 1, 2010

String Functions  addcslashes — Quote string with slashes in a C style  addslashes — Quote string with slashes  bin2hex — Convert binary data into hexadecimal representation  chop — Alias of rtrim  chr — Return a specific character  chunk_split — Split a string into smaller chunks  convert_cyr_string — Convert from one Cyrillic character set to another  convert_uudecode — Decode a uuencoded string  convert_uuencode — Uuencode a string  count_chars — Return information about characters used in a string  crc32 — Calculates the crc32 polynomial of a string  crypt — One-way string hashing  echo — Output one or more strings  explode — Split a string by string  fprintf — Write a formatted string to a stream  get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities  hebrev — Convert logical Hebrew text to visual text  hebrevc — Convert logical Hebrew text to visual text with newline conversion  html_entity_decode — Convert all HTML entities to their applicable characters  htmlentities — Convert all applicable characters to HTML entities  htmlspecialchars_decode — Convert special HTML entities back to characters  htmlspecialchars — Convert special characters to HTML entities  implode — Join array elements with a string  join — Alias of implode  lcfirst — Make a string's first character lowercase  levenshtein — Calculate Levenshtein distance between two strings  localeconv — Get numeric formatting information  ltrim — Strip whitespace (or other characters) from the beginning of a string  md5_file — Calculates the md5 hash of a given file  md5 — Calculate the md5 hash of a string  metaphone — Calculate the metaphone key of a string  money_format — Formats a number as a currency string  nl_langinfo — Query language and locale information  nl2br — Inserts HTML line breaks before all newlines in a string  number_format — Format a number with grouped thousands  ord — Return ASCII value of character  parse_str — Parses the string into variables  print — Output a string  printf — Output a formatted string  quoted_printable_decode — Convert a quoted-printable string to an 8 bit string  quoted_printable_encode — Convert a 8 bit string to a quoted-printable string  quotemeta — Quote meta characters  rtrim — Strip whitespace (or other characters) from the end of a string  setlocale — Set locale information  sha1_file — Calculate the sha1 hash of a file  sha1 — Calculate the sha1 hash of a string  similar_text — Calculate the similarity between two strings  soundex — Calculate the soundex key of a string  sprintf — Return a formatted string  sscanf — Parses input from a string according to a format  str_getcsv — Parse a CSV string into an array  str_ireplace — Case-insensitive version of str_replace.  str_pad — Pad a string to a certain length with another string  str_repeat — Repeat a string  str_replace — Replace all occurrences of the search string with the replacement string  str_rot13 — Perform the rot13 transform on a string  str_shuffle — Randomly shuffles a string Jan Zumwalt – neatinfo. 2010 .com Pg 6 of 55 rev April 1.

 strstr — Find first occurrence of a string  strtok — Tokenize string  strtolower — Make a string lowercase  strtoupper — Make a string uppercase  strtr — Translate certain characters  substr_compare — Binary safe comparison of 2 strings from an offset. Example . Tip: The print() function is slightly slower than echo(). symbols. Sometimes we need escape special characters in our strings. We will learn about in the following section. Special characters are escaped using backslash. you can use a single quotes with in double quotes. 2010 . For example. Jan Zumwalt – neatinfo. echo $str ?> Single and Double Quotes Double quotes allow us to escape specials characters in our string.PHP String <?php $str = "I Love PHP". up to length characters  substr_count — Count the number of substring occurrences  substr_replace — Replace text within a portion of a string  substr — Return part of a string  trim — Strip whitespace (or other characters) from the beginning and end of a string  ucfirst — Make a string's first character uppercase  ucwords — Uppercase the first character of each word in a string  vfprintf — Write a formatted string to a stream  vprintf — Output a formatted string  vsprintf — Return a formatted string  wordwrap — Wraps a string to a given number of characters A string is a sequence of letters.  str_split — Convert a string to an array  str_word_count — Return information about words used in a string  strcasecmp — Binary safe case-insensitive string comparison  strchr — Alias of strstr  strcmp — Binary safe string comparison  strcoll — Locale based string comparison  strcspn — Find length of initial segment not matching mask  strip_tags — Strip HTML and PHP tags from a string  stripcslashes — Un-quote string quoted with addcslashes  stripos — Find position of first occurrence of a case-insensitive string  stripslashes — Un-quotes a quoted string  stristr — Case-insensitive strstr  strlen — Get string length  strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm  strnatcmp — String comparisons using a "natural order" algorithm  strncasecmp — Binary safe case-insensitive string comparison of the first n characters  strncmp — Binary safe string comparison of the first n characters  strpbrk — Search a string for any of a set of characters  strpos — Find position of first occurrence of a string  strrchr — Find the last occurrence of a character in a string  strrev — Reverse a string  strripos — Find position of last occurrence of a case-insensitive string in a string  strrpos — Find position of last occurrence of a char in a string  strspn — Finds the length of the first segment of a string consisting entirely of characters contained within a given mask.com Pg 7 of 55 rev April 1. characters and numbers or combination of all tied together in single or double quotes.

We can escape characters in single quotes too. Single quotes should be used when outputting HTML code. ?> or <?php $name = "Matt". We can have a special character ignored by preceding it with a backslash.'.String in Single Quotes <?php $str = 'This is a PHP string examples in single quotes'. ?> or <?php print ' <center><h1>Important</h1></center> <p>This si a lot of html code<br /> that can be displayed using a<br /> single print statement and single<br /> quote</p> ' // end of print ?> Single quotes allow double quotes in the string. ?> Jan Zumwalt – neatinfo. echo "Hello $name!". ?> Example . <?php $str = 'It\'s a nice day today.Example . echo $str. echo '<input type="text" name="first_name" id="first_name">'. 2010 . <?php $str = "\"This is a PHP string examples in double quotes\"".com Pg 8 of 55 rev April 1." echo $str. echo $str. ?> Double quotes allow single quotes and special characters to be used. echo $str.String in Double Quotes <?php $str = "It's a nice day today.

?> Result: "HELLO!" ucfirst() – first letter to upper case <?php $str = "hello!". we need to join two strings.Concatenating PHP Strings <?php $str1 = "I Love PHP.com Pg 9 of 55 rev April 1. ?> strlen() . echo $str2.". echo str_replace("Hello". echo $str1. Example 1 . str_replace() . ?> Example 2 – Alternate method <?php $str1 = "I Love PHP. ?> Result: "Hello!" trim() . ?> Result: "Hi! How are you today?" strtoupper() – convert to upper case <?php $str = "hello!"." ". In PHP.replaces all occurrences <?php $str = "Hello! How are you today?". ?> Result: 6.".number of characters in a string <?php $str = "Hello!". "Hi". $str2 = $str1. $str)." PHP is fun to learn.' to concatenate two or more strings together to form a single string.$str2.Concatenating Sometimes while working with strings in our code.". echo strlen($str).remove start and end blanks Jan Zumwalt – neatinfo. you can use '. $str2 = "PHP is fun to learn. echo strtoupper($str). 2010 . echo ucfirst($str).".

?> Result: "hello!" Jan Zumwalt – neatinfo. echo trim($str).com Pg 10 of 55 rev April 1. 2010 . <?php $str = " hello! ".

Without Curly Brackets If there is only one line of code between the conditions. } or if (condition1){ statement(s). } elseif (condition2){ statement(s).If Else Statement if (condition1){ statement(s). if ($day == "Saturday") echo "It's party time :)".". ?> </body> </html> Example – With Curly Brackets <html> <body> <?php //Give what day of the week it is. Returns Sunday through Saturday. } elseif (condition2){ statement(s). } else { statement(s). <html> <body> <?php //Give what day of the week it is. } or if (condition1){ statement(s). } or if (condition1){ statement(s). Returns Sunday through Saturday. else echo "Ahhh! I hate work days. $day = date("l").com Pg 11 of 55 rev April 1. the brackets are not needed. $day = date("l"). if ($day == "Saturday") { Jan Zumwalt – neatinfo. 2010 . } else { statement(s). } Example .

} ?> </body> </html> Example .com Pg 12 of 55 rev April 1. echo " Where are you going this evening?". if ($day == "Saturday") { echo "It's party time :)". } else { echo "Ahhh! I hate work days.".". Returns Sunday through Saturday. 2010 . } else { echo "Ahhh! I hate work days. } elseif ($day == "Friday") { echo "Have a nice day!". echo " I want weekend to come :)". echo "It's party time :)".Elseif Statement <html> <body> <?php //Give what day of the week it is. $day = date("l"). echo " I want weekend to come :)". echo " Where are you going this evening?". } ?> </body> </html> Jan Zumwalt – neatinfo.

e. ?> Jan Zumwalt – neatinfo. In the third statement. we set $i to increment by 1. echo "</td>". echo "<td style='background-color:red'>".Print table with alternate colors using PHP For Loop You often seen tables cell with alternate colors on different websites. we set a counter variable $i to 0. This is how we would do it. $i=$i+1) { 1 if($i % 2 == 0) 2 { 3 echo "<tr>". $i=$i+2. 2010 . In the above example. i. echo "<td style='background-color:green'>". } ?> Result: numbers will be output 0 to 5 as 0 1 2 3 4 5. 5 echo "</td>". 0 for($i=0. 4 echo $i.com Pg 13 of 55 rev April 1. In this case the code will produce 0 2 4. <?php echo "<table width='100' align='center'>". } } echo "</table>". $i<=5." ". increment) { //execute block of code } Example . echo $i. we set the condition value to our counter variable $i to 5. $i<=5. the loop will execute until $i reaches 5. In our above example. So. i. This code will output numbers 0 to 5 as 0 1 2 3 4 5. } else { echo "<tr>". condition. In the second statement of the for loop. For Loop <?php for($i=0. Note: The third increment statement can be set to increment by any number.. Example . $i=$i+1) { echo $i. echo "</tr>".e. we can set $i to increment by 2. let say we want to print the numbers in a table with alternate colors.For Loops for(initialize. echo "</tr>".

} ?> Result: The loop outputs. echo $i . 2010 .com Pg 14 of 55 rev April 1. "<br>". } ?> Result: prints integers through 1 to 5 Breaking out of a PHP Loop Sometimes when we are working with loops.While Loop <?php $i = 1.. "<br>". <?php $i = 1. We can use the break.. 1 2 3 then breaks Jan Zumwalt – neatinfo. statement to stop the loop from executing. while ($i <= 5 ) { echo $i .While Loops While Loop Syntax while(condition) { //execute block of code } Example . we want to break the loop when a certain condition is true. $i = $i + 1. $i = $i + 1. while ($i <= 5 ) { if($i == 4) break.

"Matt". echo "The third employee's name is ". • Numeric Arrays • Associative Arrays Numeric Arrays In a numeric array we store each element with a numeric ID key. echo "The first employee's name is ". Example 3 .$employee_title["Matt"].$employee_names[0].Associative Array – (key-value pairs) <?php $employee_title["Dana"] = "Owner". echo "The third employee's name is ". echo "<br>".Numeric Array – inline assignment <?php $employee_names = array("Dana".Arrays There are two types of arrays we deal with in PHP. Example 2 . echo "The second employee's name is ".$employee_names[2].com Pg 15 of 55 rev April 1.$employee_names[1]. ?> Result: "The third employee's name is Susan". Jan Zumwalt – neatinfo. ?> Example 4 . ?> Result: "Matt is the Manger". echo "<br>". Lets look at each example to see how we do that. $employee_names[1] = "Matt".Numeric Array – individual assignment <?php $employee_names[0] = "Dana". $employee_title["Matt"] = "Manager". $employee_title["Susan"] = "Cashier". ?> Result: "The first employee's name is Dana". Creating an Numeric Array There are two ways to create a numeric array. Example 1 . $employee_names[2] = "Susan". "The second employee's name is Matt". "Susan" => "Cashier").$employee_names["Matt"]. "Susan"). 2010 . echo "Matt is the ". "Matt" => "Manager". echo "Matt is the ".Associative Array – Object (pointer) syntax <?php $employee_names = array("Dana" => "Owner". "The third employee's name is Susan".$employee_names[2].

"title" => "Owner".000".000". that's nice but how the heck would I store employees table in an array? Simple. 2010 .Pointer Multidimensional Arrays <?php $employees = array ( "employee 1" => array ( "name" => "Dana". "salary" => "$40.000 Hmmm.000". " is the ".Multidimensional Arrays Lets extend our idea of associating a single key to an element. "employee 2" => array ( "name" => "Matt". Example 6 .$employees["employee 2"]["title"]. ?> The above code creates an multidimensional array name employees and outputs "Matt is the Manager and he earns $40. Jan Zumwalt – neatinfo. Employees Table/Matrix name title salary employee 1 Dana Owner $60. $employees["employee 2"]["salary"] = "$40. Example 5 – Associative Multidimensional Arrays <?php $employees["employee 1"]["name"] = "Dana". PHP allows us to do that using multidimensional arrays. $employees["employee 3"]["name"] = "Susan". $employees["employee 3"]["salary"] = "$30. "title" => "Manager". Creating Multidimensional Array in PHP Again.$employees["employee 2"]["salary"]. $employees["employee 2"]["title"] = "Manager". $employees["employee 1"]["salary"] = "$60. Let's look at the examples below to see how we would do that. $employees["employee 3"]["title"] = "Cashier".".000". "salary" => "$60. echo $employees["employee 2"]["name"].000". " and he earns ".". $employees["employee 1"]["title"] = "Owner". Lets look at each example to see how we do that.000 employee 3 Susan Clerk $30. $employees["employee 2"]["name"] = "Matt".000 a year. What if we want to associate multiple keys to an element? Consider the Employees Table/Matrix below.000 employee 2 Matt Manager $40. ).com Pg 16 of 55 rev April 1. ). there are two ways to create a multidimensional array. " a year.

?> The array result will print out as follow..$employees["employee 1"]["title"].000".. "title" => "Cashier". echo "<pre>". $employee_title["Matt"] = "Manager". print_r($employee_title). "employee 3" => array ( "name" => "Susan".000 a year. Jan Zumwalt – neatinfo. See example below. ?> The above code creates an multidimensional array name employees and outputs "Dana is the Owner and they earn $60." print_r() . ) ). echo "</pre>". 2010 .com Pg 17 of 55 rev April 1.Printing Arrays To print the results of an array you can use the PHP function print_r() to print an array. $employee_title["Susan"] = "Cashier". <?php $employee_title["Dana"] = "Owner".$employees["employee 1"]["salary"]. " and they earn ".". "salary" => "$30. " a year. Array ( [Dana] => Owner [Matt] => Manager [Susan] => Cashier ) Note: Always remember to use <pre></pre> tags while printing an array as shown above otherwise the result is not very reader friendly. echo $employees["employee 1"]["name"]. " is the ".

date("Y-m-d". ?> Result: yesterday was 2010-03-18 Find Date one week ago <?php echo "1 week from today was ". strtotime("-1 weeks")).Month representation in numbers. Y").Year in four digits timestamp. This is also known as the Unix Timestamp. 2010. Y"). 2010 . 04:20:36 echo date("l F d. 2010. 2010 echo date("l F d. // Friday March 19. 2.date("Y-m-d". Y. // Friday March 19. 2010 echo date("l F d. // March 19. // 2010-03-19 echo date("Y/m/d"). h:i A"). 01-12 Y . h:i:s"). 1.Convert any English textual datetime description into a Unix timestamp. // 2010-03-19 echo date("M d. i. is an optional parameter representing the number of seconds since January 1. 04:20 PM ?> Where: d .e. 1970 at 00:00:00 GMT. Y. 2010 echo date("D M d. strtotime . // Friday March 19. strtotime("-1 days")). Y"). There are two ways we can do that. PHP Date: strtotime() Using the we can find exact dates or days. strtotime("+1 months")). // Fri Mar 19. 2010 echo date("F d. // Mar 19. i. 01-31 m .The day of the month. timestamp]) <?php echo date("Y-m-d").Get Unix timestamp for a date. Y"). ?> Result: 1 week from today was 2010-03-12 Find Date one month after <?php echo "1 month from today will be ".Date & Time PHP Date Function Syntax date(format[.date("Y-m-d". mktime . ?> Result: 1 month form today will be 2010-04-19 Jan Zumwalt – neatinfo.com Pg 18 of 55 rev April 1.e. Find Yesterday’s date <?php echo "yesterday was ".

3. file pointer at beginning of file and truncate the file 'w+' to zero length. 2.The number of seconds past the minute. 29. day . Open for read/write. mktime(0. /* * since leap year falls ever 4 years so loop for 4 times */ for($i=0. it attempt to create it. 0. then it not a leap year. 2. If the file does not exist. $i<4. Open for write only. If file does not 'a' exist. place the file pointer at the beginning of the file. 1. file pointer at the end of the file. } } echo "next leap year is in year $year". Open for writing only. date("Y")+$i)).PHP Date: mktime() mktime is used to find more specific things like the next leap year. 0. PHP file open modes 'r' Open for reading only. Local File IO fopen ($filename. 6. If file does not exist.The number of year. minute . * If day is 29 then it must be the leap year. place the file pointer at the beginning of the 'r+' file. create it. hour . place the file pointer at the beginning of the file and 'w' truncate the file to zero length. Find Leap Year <?php $day = "". ?> Result: next leap year is in year 2012 The mktime takes 6 arguments.The number of the hour. create it.com Pg 19 of 55 rev April 1. 5. 2010 . /* * check if day equals 29. 4. Jan Zumwalt – neatinfo.The number of the month.The number of the minute. month . The parameters are explained as below. Open for reading and writing. if day is 01. $i++) { //get day timestamp for feburary 29 for this year $day = date("d". year . second . break.The number of the day. */ if($day == 29) { $year = date("Y")+$i. $mode).

txt for reading and places the pointer at the beginning of the files. ?> Result: Opens myfile. 2010 . • $handle . fgets ($handle. pointer at beginning of file. Note: If line exceeds 1024 characters. "r"). Example 1 . Example 2 . The first parameter is the file pointer and the 2nd parameter which is optional is the number of bytes to read in one call. Using this function we either read the entire line into a string or specify the number characters we like to read. it is advisable to read only up to maximum of 1024 characters at a time for not using up lot of memory. fgets() – Read Line The fgets() functions is used to read a line from a file.txt doesn't exist. If you like to create the file in case it doesn't exist. 'a+' If the file does not exist. "r+"). you can use the file mode 'a'. $length). Open for reading and writing.txt". If length is not specified it will read at the end of the line.the file pointer • $length . What happens if the file doesn't exist? If the myfile. If the 2nd parameter is not giving.txt". attempt to create it. the function will read at the end of the line.open file for reading and writing <?php $fh = fopen(" myfile.open file for reading <?php $fh = fopen("myfile..number of bytes to read. ?> Result: Opens myfile.. Let’s looks at the function more closely. What if I want to place pointer at the end of a file? For that you can use file mode 'a' and 'a+' respectively to read/write from the end of the file. place the file pointer at the end of the file. The fgets() function has two parameter. if($fh==false) die("unable to create file"). the file handle $fh will return false. Jan Zumwalt – neatinfo. In this section we are going to cover how to open and read file content in PHP. This will create a new file myfile. if it doesn't already exists. if($fh==false) die("unable to create file").txt.com Pg 20 of 55 rev April 1.txt for r/w.

echo $str. if($line == null)break. Example 1 .txt". $line = fgets($fh). 64). <?php $fh = fopen("myfile. $str = fgets($fh. "r"). } fclose($fh). <?php $fh = fopen("myfile. fclose($fh). Let's look at two different examples to see how we can do that.txt". "r"). ?> In the above we didn't specify how many bytes we want to read.reading file line by line <?php $fh = fopen("myfile. ?> The above code reads the first 64 characters and then reads the next 64 characters in the line. let's look at some example of how to read from a file. $line2 = fgets($fh. 64). echo $line.txt".com Pg 21 of 55 rev April 1. we use the same method to read only certain number of characters in a line.Now. Reading number of bytes In this second example. The code will start off by placing the file pointer at the beginning of the file and then reading the first line in our file into a string. the entire line is read. ?> Jan Zumwalt – neatinfo. 2010 . while(true) { $line = fgets($fh). echo $line. "r"). the mode 'r' means we are opening the file for reading only. Therefore. Remember. fclose($fh). echo $str. Reading file line by line Using the fgets() function we can also read the entire file line by line in one loop. Reading entire line The following code reads a line from a file into a string.

But first.txt". the string to be written and the number of bytes to be written.Example 2 . "r").read entire file In some cases you might need to read the entire file at once. $length). your script/application might hang due to lack of resources.txt". Either you should split the file into two or more pieces or utilize more smart ways of reading a file. while (!feof($fh)) { $line = fgets($fh). } fclose($fh).txt into the string $file. It is not advisable to read big files in one go. you must make sure to open file in writable mode before writing.com Pg 22 of 55 rev April 1. 2010 .txt"). The fwrite() function takes three arguments. ?> The above code will read the entire file content of myfile. <?php $fh = fopen("myfile. let's examine the fwrite() the function closely. • $handle – the file stream • $string – string to be written in file • $length – optional. $string. We can easily write text to files using the fwrite() function. echo $file.reading file line by line <?php $fh = fopen("myfile. $file = file_get_contents("myfile. Jan Zumwalt – neatinfo. which is optional. You will see which modes to use when writing to files and how to write to files in examples below. let's work with some examples below on how to write text to files. fwrite($handle. "r"). Now. the file handle. echo $line. fwrite() – writing to file Writing text to files is fairly easy in PHP. However. Please note that if the file is fairly large. ?> file_get_contents() . Number of bytes to write in file. Once such function is file_get_contents() Let's look at an example of how to use this function. Reading the file line by line is probably more work in that case. In this case you can utilize other functions that will read the entire file content in a string in one go.

com Pg 23 of 55 rev April 1. Write at the beginning of a file Using file open mode "a+". "Student Name: Mark Fendisen")) die("couldn't write to file. which means that anything already in the file is left alone. that is.txt". if($handle) { if(!fwrite($handle. rewind($handle).txt". If the file doesn't exists. That was fairly easy I would say. Wasn't it? Note: "w+" truncates the file to zero. } //place pointer at the beginning of the file. 'w+'). echo "success writing to file". the file pointer is placed at the end of the file but remember we want to write at the beginning of the file. 'a+'). and the new string in written in the beginning of the file. deletes everything in the file before writing. you can append text to either beginning or end of a file. The code below writes the string "Student ID: 12345" in the beginning without truncating the file. In other words.txt in writable mode using "w+" and writes "Student Name: Mark Fendisen" into the file. When you open a file with mode 'a+'. //write to file Jan Zumwalt – neatinfo. if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name. if(!$handle) { die("couldn't open file <i>$file_name</i>"). The first thing we need to do is open the file in append mode using 'a+'. } ?> <pre> The above code creates a new file myfile. We will see how we can do in the examples below The first example we tackle is. <?php $handle = fopen("myfile. <?php $file_name= "myfile. we can use the function rewind() as seen below. how to write text at the beginning of a file. 2010 ."). To move the file pointer back to the beginning for writing. open an existing file so that we can add more stuff to it. it create a new file.Write text to a file The first example demonstrates how to write a single line of text to a file.

= "Student Name: Mark Fendisen\r\n".txt". } else { echo "file <i>$file_name</i> doesn't exists". } else { echo "file <i>$file_name</i> doesn't exists". echo "success writing to file". if(!$handle) { die("couldn't open file <i>$file_name</i>"). you can use both together like this "\r\n" regardless of what system you're running your code on.9"). $str. } fclose($handle). If you are using PC. 'a+'). ?> Write at the end of a file As seen in the above example.= "Student ID: 12345\r\n". "Student GPA: 2. use "\r". } fwrite($handle. Jan Zumwalt – neatinfo. if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name. the mode "a+" automatically places the file pointer at the end of the file so we don't have to do anything extra in this case. 'w').com Pg 24 of 55 rev April 1. if(!$handle) { die("couldn't open file <i>$file_name</i>"). } $str. For Macintosh. fwrite($handle. <?php $file_name= "myfile. use "\n". But just to be on the safe side. we can write text one per line in a file by using carriage return. ?> Write string with line breaks The examples you saw so far write text in one straight line.9" at the end of the file. What if we want line breaks? Well. This will guarantee it works under both PCs and Macintosh. '\n' or '\r'.txt". echo "success writing to file". The code below writes "Student GPA: 2. 2010 . if(file_exists($file_name)) { //open file for writng and place pointer at the end $handle = fopen($file_name. <?php $file_name = "myfile. } fclose($handle). "Student ID: 12345").

e. read file line by line and overwrite small part of text in a file with new string.9 with 3. 'r+'). "Student GPA: 3. 2010 .txt". With me? That's okay if you're not :) Let's examine the code below and you will understand what we have done.9\r\n".9 What we want to do is update his GPA from 2. } else { //set file content to a string Jan Zumwalt – neatinfo. For our example below we will assume we have file which contains the following information about a student. $str). i. echo "success writing to file".= "Student GPA: 2.9 from 3. $line). } fclose($handle). //if end of file reached then stop reading anymore if($line == null)break. ?> Simultaneous Read / Write Most often you will find yourself reading and writing to a file at the same time.9". * Place pointer at the beginning of the file. */ $handle = fopen($file_name. The example below shows you how to parse data in a file. Next. <?php $file_name= "myfile. fwrite($handle.1 and write the new string back to the file.1".com Pg 25 of 55 rev April 1. } else { echo "file <i>$file_name</i> doesn't exists". we read the file line by line using fgets function until we reach the student gpa line. We then use string replace function to replace 2. Student Name: Mark Fendisen Student ID: 12345 Student GPA: 2. How would we do it? First we need to open the file in both read and write mode using "r+". if(file_exists($file_name)) { /* Open file for both reading and writng. //replace student gpa with new updated gpa if(preg_match("/Student GPA:/". $line)) { $new_line = str_replace("Student GPA: 2. if(!$handle) { die("couldn't open file <i>$file_name</i>"). $str. } while(1) { //read line $line = fgets($handle).1.

//write everything back to file with the updated gpa line fwrite($handle. //delete everything in the file. } else { echo "file <i>$file_name</i> doesn't exists". } fclose($handle).1 The above code is fairly large. in this lesson we covered. ?> Result: Student Name: Mark Fendisen Student ID: 12345 Student GPA: 3. ftruncate($handle. filesize($file_name)). how to write text to files in different scenarios. In summary.com Pg 26 of 55 rev April 1. I would recommend to go over it slowly and read the internal comments in the code to understand how it is done. } } //append new updated gpa to file content $str. Knowing how to work with files can be very useful when developing. I would advise to do some practice examples to get a hang of things before moving on. 2010 . //set pointer back to beginning rewind($handle). echo "success writing to file".= $new_line. $str). $str.= $line. Jan Zumwalt – neatinfo.

$errstr. } fclose($fp). "Host: www. } ?> So. Example 1 . 2010 . while (!feof($fp)) { echo fgets($fp. $port.1\r\n"). fputs($fp. $errno .com\r\n"). unless otherwise told. <?php $fp = fsockopen("www. In the next tutorial.open remote files The example below shows how to read the source code of a page and display it. optional. 80. } else { fputs($fp. "Connection: Close\r\n\r\n"). $errno.Remote File IO fsockopen($hostname. $port . $errstr. optional. fputs($fp.somedomain. $errno. $timeout).com". contains error message during connection $timeout . the default port is 80. Jan Zumwalt – neatinfo. seconds before connection timeout error. we will cover how to read from files and how to write to files. 30).com Pg 27 of 55 rev April 1. "GET / HTTP/1. where: $hostname . if ($fp == false) { echo "$errstr ($errno)". location or URL of the file or page. optional. 1024). contains error number during connection.somedomain. $errstr . in this tutorial we learned how to open files for reading and writing.

print "Your email: $vmail<br />".php <html> <head> <head><title>Simple php form visitor_info. print "You name: $vname<br />".php">Your Name: <br /> <input type="text" name="visitorname" size="35" /> <br /><br /> Your Email:<br /> <input type="text" name="visitormail" size="35" /> <br /> <br /> Age:<br /> <select name="visitorage" size="1"> <option value="0-10">0-10</option> <option value="11-25">11-25</option> <option value="26-50">26-50</option> <option value="50+">over 50</option> </select> <br /><br /> <input type="submit" value="Send Info" /> <br /> </form> ' // end of print ?> </body> </html> Process form – visitor_info. Y. saved or displayed.php <html> <head><title>Simple php form visitor_form. then it must be processed i. F j.php</title></head> <body> <?php print ' <form method="post" action="visitor_info.Forms Processing a remote form is a two step process.com Pg 28 of 55 rev April 1.php</title></head> </head> <body> <h1> PHP simple form processing </h1> <?php $vname = $_POST['visitorname']. print "Today's date: $todayis<br />". g:i a"). $todayis = date("l. Input form – visitor_form. 2010 . First you must input the data. print "Your age: $vage<br />". $vmail = $_POST['visitormail'].php"> back to form </a> </body> </html> Jan Zumwalt – neatinfo.e. ?> <br /> <a href="visitor_form. $vage = $_POST['visitorage'].

?> In our send_email function we set the appropriate headers. Sending HTML Email The following function will send out an HTML formatted email using the PHP built in mail function. $headers ."\r\n".$from.= "Return-Path: ". $headers . "hidden_email@domain. $message){ $headers = "From: ".= "Reply-To: ".com". CC and BCC.the email message to be sent. headers .= "CC: ".= "Reply-To: ".$headers) ) { echo "email sent"."\r\n".$cc. $message = "Hello! How are you today?".Email mail($to. "recpeient@domain.$from. $headers .$from.com". $subject. $headers .the subject of the email. if (mail($to. $subject. 2010 . Next we call the send_email function which sends out the email. senders name and email. $headers)."\r\n". } else { Jan Zumwalt – neatinfo. so it's good to leave it in there. $subject .$subject.= "BCC: "."\r\n".$message. $to.= "Content-type: text/html\r\n".$subject.$headers) ) { echo "email sent"."\r\n". where: to .the recipients email address subject . $message. } } $subject = "Hello!". <?php function send_email($from. if (mail($to. } else { echo "email could not be sent". $cc. $headers .the header contains information such as the format of the email (plain text or HTML). $message){ $headers = "From: ". Sending Plain Text Email The following code will send out a plain text email using the PHP built in mail function. send_email("youraddress@domain. $bcc. Some server requires the use of Return-Path. $headers . $message).com Pg 29 of 55 rev April 1. Reply-To and Return- Path points to the email you want the recipient to reply to."\r\n".com"."\r\n".= "Return-Path: ". $to. message .$from. reply to address.$to. <?php function send_email($from. $subject.com"."\r\n".$from.$message. $headers . "someone@domain.$from.

com Pg 30 of 55 rev April 1. $message).= "<b>Hey! How are you today?</b>".com".= "</body></html>". 2010 . It is important to do so because it tells the email server that the email contains html code and to format and display the email correctly when it is opened.php <html> <head> <meta http-equiv="Content-Type" content="text/html. echo "email couldn't be sent". ?> <input type="hidden" name="ip" value="<?php echo $ipi ?>" /> <input type="hidden" name="httpref" value="<?php echo $httprefi ?>" /> <input type="hidden" name="httpagent" value="<?php echo $httpagenti ?>" /> Your Name: <br /> <input type="text" name="visitor" size="35" /> <br /> Your Email:<br /> <input type="text" name="visitormail" size="35" /> <br /> <br /> <br /> Attention:<br /> <select name="attn" size="1"> <option value=" Sales n Billing ">Sales n Billing </option> <option value=" General Support ">General Support </option> <option value=" Technical Support ">Technical Support </option> <option value=" Webmaster ">Webmaster </option> </select> <br /><br /> Mail Message: <br /> <textarea name="notes" rows="4" cols="40"></textarea> <br /><br /> <input type="submit" value="Send Mail" /> <br /> </form> Jan Zumwalt – neatinfo. $message .com". "recpeient@domain. ?> In our send_email function we set the content type headers to text/html. } } $subject = "Helloooo!". send_email("youraddress@domain.DO NOT change ANY of the php sections --> <?php $ipi = getenv("REMOTE_ADDR"). $subject . Remote input and processing Email This is an example of an email input form that is sent to a php file for processing.= "<html><body>".php"> <!-. $message . $message . charset=utf-8" /> <title>Email Form </title> </head> <body> <form method="post" action="sendmail. $message . $httprefi = getenv ("HTTP_REFERER"). $httpagenti = getenv ("HTTP_USER_AGENT").= "<br>Regards". Input form – email.

die ("Go back! ! ").Reminder: Add the link for the 'next page' (at the bottom) --> <!-. $attn = $_POST['attn']. } if(!$visitormail == "" && (!strstr($visitormail. $httpref = $_POST['httpref']. die ("Use back! ! "). $badinput = "<h2>Feedback was NOT submitted</h2>\n".".Enter valid e-mail</h2>\n". 2010 . $visitor = $_POST['visitor']. mail("YourEmail".Reminder: Change 'YourEmail' to Your real email --> <?php $ip = $_POST['ip']. $subject. } if(empty($visitor) || empty($visitormail) || empty($notes )) { echo "<h2>Use Back . $subject = $attn. </body> </html> Processing program – sendmail. F j. echo $badinput. $from = "From: $visitormail\r\n". $notes)) { die ("Do NOT try that! ! "). $visitormail = $_POST['visitormail']. if (eregi('http:'. g:i a") .fill in all fields</h2>\n". $notes = $_POST['notes']."@") || !strstr($visitormail. $message = " $todayis [EST] \n Attention: $attn \n Message: $notes \n From: $visitor ($visitormail)\n Additional Info : IP = $ip \n Browser Info: $httpagent \n Referral : $httpref \n ". $attn = $attn . $notes = stripcslashes($notes). charset=utf-8" /> <title>Sendemail Script</title> </head> <body> <!-. Y.php <html> <head> <meta http-equiv="Content-Type" content="text/html."))) { echo "<h2>Use Back . $from). $httpagent = $_POST['httpagent'].com Pg 31 of 55 rev April 1. } $todayis = date("l. $message. ?> <p align="center"> Date: <?php echo $todayis ?> <br /> Thank You : <?php echo $visitor ?> ( <?php echo $visitormail ?> ) <br /> Jan Zumwalt – neatinfo.

"<br/>". $notes).com Pg 32 of 55 rev April 1. ?> <br /> <?php echo $ip ?> <br /><br /> <a href="email.php"> Next Page </a> </p> </body> </html> Jan Zumwalt – neatinfo. 2010 . Attention: <?php echo $attn ?> <br /> Message:<br /> <?php $notesout = str_replace("\r". echo $notesout.

The code above starts a session for the user on the server. Now lets learn how we create a session in PHP Before you can store any information in session variables. <?php session_start(). and assign a session id for that user's session. 2010 . See below.Sessions In PHP. echo $_SESSION["username"]. You can access the session id using the PHP predefined constant PHPSESSID. ?> <html> <body> </body> </html> When you start a session a unique session id (PHPSESSID) for each visitor/user is created.com Pg 33 of 55 rev April 1. You can access the stored session information on any page without doing anything extra. echo "<br/>". ?> Retrieving stored session information Retrieving stored session information is really easy. $_SESSION["color"] = "blue". you must first start up the session using the session_start() function. echo $_SESSION["color"]. $_SESSION["username"] = "johny". ?> Result: Johny blue Jan Zumwalt – neatinfo. <?php session_start(). Note: The session_start() function must appear BEFORE the <html> tag Storing information in a session To store information is a session variable. you must use the predefined session variable $_SESSION. information is stored in session variables. <?php session_start().

2010 . but if you wish to clear a session variable yourself.Destroying/deleting session information Remember sessions are destroyed automatically after user leaves your website or closes the browser. unset($_SESSION["color"]). ?> To completely destroy all session variables in one go. you can simple use the unset() function to clean the session variable.com Pg 34 of 55 rev April 1. unset($_SESSION["username"]). <?php session_start(). you can use the session_destroy() function. <?php session_destroy(). ?> Jan Zumwalt – neatinfo.

the cookie will be available through out the whole site.com". Cookie is set to expire after one hour. $path. $domain.com Pg 35 of 55 rev April 1. Example: time()+"3600". if the path is set to "/". The function time() retrieves the current timestamp. if the domain is set to ". Note: A cookie must be set before any HTML code as shown above.yourdomain. "john". For example. for example.Cookies A cookie is often used to store data which can be used to identify a user. $secure) $name . setcookie($name. Instead of path you can use domain settings.name of the cookie.value of the cookie. "john". all cookie information is sent too. This is used to identify who you are. person's username.path on the server where cookie will be available.yourdomian. ?> <html> <body> </body> </html> Cookie username is set with value john which is set to expire after one hour on users computer. <?php setcookie("username". Cookie is a small flat file which sits on user’s computer.com/news" $secure . cookie in created under the current directory. ?> Retrieving a cookie Cookie information is retrieved using the predefined $_COOKIE array. Each time that user requests a page or goes to a webpage.yourdomian. the cookie will be available within the domain and all its sub-domains. Appending 3600 seconds (one hour) to the current time to make the cookie to expire after one hour. 2010 . Default value is false. false otherwise. the cookie will only be available under /news/ and all its sub- directories. If the cookie is set to say "/news/".com" the cookie will be available under all www sub-domains. <?php setcookie("username". The following will retrieve our username cookie value Jan Zumwalt – neatinfo. time()+(60*60*24*365)). $domain .true if cookie is being set over a secure "https" server. If the cookie is set say "www. Creating a permanent cookie Lets create a cookie which is set to last for 1 year. $value. Example: "username" $value .yourdomian. If no path is given.com. example news.domain where cookie will be available. $expire. For example.time (in UNIX timestamp) when the cookie will expire. example " www. time()+3600). Example: "john" $expire . $path .

?> Result: Array ( [username] => john ) Deleting a Cookie In order to delete cookies. "john". time()-(60*60*24*365)). echo "</pre>". print_r($_COOKIE). <?php setcookie("username". you just set the cookie to expire in the past date. <?php echo $_COOKIE["username"]. ?> Jan Zumwalt – neatinfo. you can do the following <?php echo "<pre>". Following will delete our username cookie.com Pg 36 of 55 rev April 1. ?> Result: john To print the entire $_COOKIE array. 2010 .

a numeric array. or both  mysql_fetch_assoc — Fetch a result row as an associative array  mysql_fetch_field — Get column information from a result and return as an object  mysql_fetch_lengths — Get the length of each output in a result  mysql_fetch_object — Fetch a result row as an object  mysql_fetch_row — Get a result row as an enumerated array  mysql_field_flags — Get the flags associated with the specified field in a result  mysql_field_len — Returns the length of the specified field  mysql_field_name — Get the name of the specified field in a result  mysql_field_seek — Set result pointer to a specified field offset  mysql_field_table — Get name of the table the specified field is in  mysql_field_type — Get the type of the specified field in a result  mysql_free_result — Free result memory  mysql_get_client_info — Get MySQL client info  mysql_get_host_info — Get MySQL host info  mysql_get_proto_info — Get MySQL protocol info  mysql_get_server_info — Get MySQL server info  mysql_info — Get information about the most recent query  mysql_insert_id — Get the ID generated in the last query  mysql_list_dbs — List databases available on a MySQL server  mysql_list_fields — List MySQL table fields  mysql_list_processes — List MySQL processes  mysql_list_tables — List tables in a MySQL database  mysql_num_fields — Get number of fields in result  mysql_num_rows — Get number of rows in result  mysql_pconnect — Open a persistent connection to a MySQL server  mysql_ping — Ping a server connection or reconnect if there is no connection  mysql_query — Send a MySQL query  mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement  mysql_result — Get result data  mysql_select_db — Select a MySQL database  mysql_set_charset — Sets the client character set  mysql_stat — Get current system status  mysql_tablename — Get table name of field  mysql_thread_id — Return the current thread ID  mysql_unbuffered_query — Send SQL query to MySQL w/out fetching and buffering the result rows.com Pg 37 of 55 rev April 1.MySql  MySQL Functions  mysql_affected_rows — Get number of affected rows in previous MySQL operation  mysql_client_encoding — Returns the name of the character set  mysql_close — Close MySQL connection  mysql_connect — Open a connection to a MySQL Server  mysql_create_db — Create a MySQL database  mysql_data_seek — Move internal result pointer  mysql_db_name — Get result data  mysql_db_query — Send a MySQL query  mysql_drop_db — Drop (delete) a MySQL database  mysql_errno — Returns the numerical value of the error message from previous MySQL operation  mysql_error — Returns the text of the error message from previous MySQL operation  mysql_escape_string — Escapes a string for use in a mysql_query  mysql_fetch_array — Fetch a result row as an associative array. Jan Zumwalt – neatinfo. 2010 .

a user name and a password. In a table you will set up the different fields which will be used in that table. nearly all of a site's database needs can be satisfied using just one database. ?> and save it as phpinfo. 2010 . If you have PHPMyAdmin (or a similar program) installed you can just go to it to log in with your user name and password. you will however end up with a database name. Creating A Table Before you can do anything with your database. Because of this construction.com Pg 38 of 55 rev April 1. A search on the internet will provide lists of all the field types allowed. This information will be required to log in to the database. It takes the following format: Jan Zumwalt – neatinfo. Open a text editor and type in the following: <? phpinfo(). If you are using a PHP script to create your database. Each of these tables is quite separate and can have different fields etc. Creating a table in PHPMyAdmin is simple. You will then be taken to a setup screen where you must create the fields for the database. select the number of fields and click the button.Setting Up The Database There is a simple test for both PHP and MySQL. Fields There are a wide variety of fields and attributes available in MySQL and I will cover a few of these here: Field Type Description TINYINT Small Integer Number SMALLINT Small Integer Number MEDIUMINT Integer Number INT Integer Number VARCHAR Text (maximum 256 characters) TEXT Text These are just a few of the fields which are available. you must create a table. just type the name. If not you must do all your database administration using PHP scripts. Databases And Logins The process of setting up a MySQL database varies from host to host. even though it is part of one database.php Database Construction MySQL databases have a standard setup. the whole creation and setup will be done in one command. in which is contained tables. A table is a section of the database for storing related information. They are made up of a database. Creating A Table With PHP To create a table in PHP is slightly more difficult than with MySQL. Each table contains records which are made up of fields.

$password="password". Creating The Table In PHP The following code should be used to create this table in PHP.$password). The id field will also be set as PRIMARY. as well as textual numbers (like 1800-COMPANY) and as we will not be initiating phone calls from the web it is not a problem.web varchar(30) NOT NULL. The following fields will be used in the database: Name Type Length Description id INT 6 A unique identifier for each record first VARCHAR 15 The person's first name last VARCHAR 15 The person's last name phone VARCHAR 20 The person's phone number mobile VARCHAR 20 The person's mobile number fax VARCHAR 20 The person's fax number email VARCHAR 30 The person's e-mail address web VARCHAR 30 The person's web address You may be wondering why I have used VARCHAR fields for the phone/fax numbers even though they are made up of digits. The reason for this is that this will be the field identifier (primary and index) and so must be unique. it will be given the next number. as long as you don't specify an id. <? $user="username".email varchar(30) NOT NULL. @mysql_select_db($database) or die( "Unable to select database").PRIMARY KEY Jan Zumwalt – neatinfo. There is one other thing you should be aware of in this database.fax varchar(20) NOT NULL. 2010 . You could use INT fields but I prefer to use VARCHAR as it will allow dashes and spaces in the number. UNIQUE and will be set to auto_increment (found under Extra in PH PMyAdmin). $database="database". I will give full an example of using these later in the section. The auto increment setting means that whenever you add a record.mobile varchar(20) NOT NULL. The final field entered should not have a comma after it. If you are using PHPMyAdmin or a management program you can now create this in a table called contacts. The Contacts Database The contacts database will contain all the conact information for the people you enter and the information will be able to be edited and viewed on the internet.com Pg 39 of 55 rev April 1.last varchar(15) NOT NULL.phone varchar(20) NOT NULL.first varchar(15) NOT NULL. INDEX. Some of the code has not been covered yet but I will explain it fully in the next part. $query="CREATE TABLE contacts (id int(6) NOT NULL auto_increment.$user. CREATE TABLE tablename { Fields } The fields are defined as follows: fieldname type(length) extra info. mysql_connect(localhost.

mysql_query($query). ?> Enter your database. MySQL username and MySQL password in the appropriate positions on the first three lines above.(id). 2010 .com Pg 40 of 55 rev April 1. Jan Zumwalt – neatinfo.KEY id_2 (id))". mysql_close().UNIQUE id (id).

if you are not connected. is used to do this.com" (including the quotes)) using the username stored in $username and the password in $password.com you should replace localhost with "sql. The following command: @mysql_select_db($database) or die( "Unable to select database").myserver. I will show you one more command: mysql_close(). This is a very important command as it closes the connection to the database server. $password="password". Unless you web host tells you otherwise you should use localhost.myserver. You don't need to worry. This line tells PHP to connect to the MySQL database server at 'localhost' (localhost means the server that the site is running one.com Pg 41 of 55 rev April 1. Selecting The Database After you have connected to the database server you must then select the database you wish to use.$username.$password). Before I show you how to work with the database. Next. to keep the server running well. Your script will still run if you do not include this command but too many open MySQL connections can cause problems for a web host. 2010 . keeping your password in the file. you will need to issue the command to start a database connection: mysql_connect(localhost.Inserting Information Over the past two parts I have explained what I am planning to do in this tutorial and have shown you how to create a database to use with the tutorial. If it cannot connect it will stop executing the script and output the text: Unable to select database This extra 'or die' part is good to leave in as it provides a little error control Jan Zumwalt – neatinfo. In this part I will be showing you how to insert some information into your database so that it is more useful. password and database name first so that if you change any of them at a later date you will only have to change one line: $username="username". because the PHP scource code is processed aby the server before being sent to the browser so it is impossible for the user to see the script's source. If you are given a server address (such as sql. Good practice for using databases is to specify the username. It is good practice to always include this line once you have issued all your commands to the database. This must be a database to which your username has access. $database="your_database". This is an extremely important step as. Connecting To The Database The first thing you must do before you can do any work at all is to connect to the MySQL database. though. This tells PHP to select the database stored in the variable $database (which you set earlier). At this point you may be wondering if it is a security risk. your commands to the database will fail.

gowansnet.'01234 567891'. No two records in the database will have the same ID. This way is used if there will be no results from the operation. For example: John will be inserted into the 2nd field which.but it is not essential. You may have noticed that you are not inserting any value into the first field in the database (id). It tells the PHP to insert into the table called contacts the values in the brackets which follow. when we set up the database we set ID to 'Auto Increment'.gowansnet.'00112 334455'. Executing Commands Now you have connected to the server and selected the database you want to work with you can begin executing commands on the server. One is to just enter the command in PHP. In this part of the tutorial we will use the first way as we are not expecting a response from the database. This means that if you assign it no value it will take the next number in the series. Firstly $query= is there because we are assigning this to the variable $query (see the section above). This means that this first record will have the ID 1.com'.'John'. All you need to do is to change the variable.'johnsmith@gowansnet. It uses all the fields in order and inserts the information from between the quotes. We will now add our first information to the database: First: John Last: Smith Phone: 01234 567890 Mobile: 00112 334455 Fax: 01234 567891 E-mail: johnsmith@gowansnet. This is because this field is going to act as an index field. The command will look like this: mysql_query($query).com Web: http://www. 2010 . The other way is to define the command as a variable.'Smith'.'http://www.com This will all be put in with one command: $query = "INSERT INTO contacts VALUES (''. Inserting Data For this part of the tutorial I will return to the contacts database which we created in the last part. This may look a little confusing at first so I will explain what it all means. The part in the brackets contains all the information to add. Jan Zumwalt – neatinfo.com Pg 42 of 55 rev April 1.'01234 567890'. The useful thing about using this form of the command is that you can just repeat the same command over and over again without learning new ones. in this table.com')". There are two ways of executing a command. is the 'first' field. This will set the variable with the results of the operation. Because of this. The next part: INSERT INTO contacts VALUES is quite easy to understand.

mysql_close(). ?> This script should then be saved as insert. HTML Input Inputing the data using HTML pages is almost identical to inserting it using a PHP script. $first=$_POST['first'].$password).'$mobile'. The following code will show an HTML page with textboxes to enter the appropriate details: <form action="insert. $fax=$_POST['fax']. $database="your_database".php so that it can be called by the HTML form. $phone=$_POST['phone']. $mobile=$_POST['mobile'].'$web')". though. It works because. $last=$_POST['last']. You could also add to this script a message confirming the data input. It is just a basic form to get you started. is that you do not need to change the script for each piece of data you want to input and you can also allow your users to input their own data. it is being entered into the form and stored in variables which are then passed to the PHP. $web=$_POST['web']. you will instead use variables: <? $username="username". In this part I will show you how to create an input page for your database. $query = "INSERT INTO contacts VALUES (''. The benefit. mysql_connect(localhost. of course. be formatted and have other changes made to it. you have created a database and put information into it. though.Displaying Data So far in this tutorial.com Pg 43 of 55 rev April 1. Outputting Data Jan Zumwalt – neatinfo. and you should read the PHP tutorial if you do not know how to do this. instead of the data being entered locally. Instead of using information to input into the database. This is basic PHP. mysql_query($query).$username.'$last'. and how to display the whole contents.'$phone'.php" method="post"> First Name: <input type="text" name="first"><br> Last Name: <input type="text" name="last"><br> Phone: <input type="text" name="phone"><br> Mobile: <input type="text" name="mobile"><br> Fax: <input type="text" name="fax"><br> E-mail: <input type="text" name="email"><br> Web: <input type="text" name="web"><br> <input type="Submit"> </form> This page could.'$fax'. @mysql_select_db($database) or die( "Unable to select database"). $password="password". Next you will need to edit the script from last week.'$first'. 2010 . $email=$_POST['email'].'$email'.

if not many more. Each time $i will be one greater than the time before.$i. $i is the number of times the loop has run and is used to make sure the loop stops at the end of the results so there are no errors.com Pg 44 of 55 rev April 1. This can then be used in a loop to get all the data and output it on the screen.Now you have at least one record. In this case the whole contents of the database is now contained in a special array with the name $result. while ($i < $num) { CODE $i++. Before you can output this data you must change each piece into a separate variable. By using $num. There are two stages to this. of course. Because there will be output from this command it must be executed with the results being assigned to a variable: $query="SELECT * FROM contacts". As the first line in MySQL output is 0. which you created above. Counting Rows Before you can go through the data in your result variable. just type this into your code but it is not a very good solution as the whole script would need to be changed every time a new row was added. In the code below. you can loop through all the rows quite easily. 2010 . as $i can be used to tell the script which line of the results should be read. $i=0. this will work correctly. Setting Up The Loop nYou must now set up a loop to take each row of the result and print out the data held there. Before beginning. So to take each individual piece of data in our database we would use the Jan Zumwalt – neatinfo. Assigning The Data To Variables The final part of this output script is to assign each piece of data to its own variable. you must know how many database rows there are. This will set the value of $num to be the number of rows stored in $result (the output you got from the database). This is useful. The first command you will need to use is a MySQL query made up like this: SELECT * FROM contacts This is a basic MySQL command which will tell the script to select all the records in the contacts table. though you should be familiar with loops in PHP (you can find out about them in the tutorial on Free Webmaster Help) as they are used for this way of outputting data. in your database you will be wanting to know how you can output this data using PHP. $result=mysql_query($query). Instead you can use the command: $num=mysql_numrows($result)."fieldname"). The following code is used to do this: $variable=mysql_result($result. You could. } This is a basic PHP loop and will execute the code the correct number of times.

$i. In this script the data is not formatted when it is output: <? $username="username". $web=mysql_result($result. $query="SELECT * FROM contacts". $mobile=mysql_result($result.$i.com Pg 45 of 55 rev April 1."phone"). mysql_close()."mobile")."last"). echo "<b><center>Database Output</center></b><br><br>". We do not need to get the ID field (although we could have done) because we have no use for it in the current output page.$username. $email=mysql_result($result."first").$password). $num=mysql_numrows($result). $fax=mysql_result($result.$i. $phone=mysql_result($result.$i."web").$i. 2010 . $last=mysql_result($result."fax"). $mobile=mysql_result($result. } ?> Jan Zumwalt – neatinfo."fax")."phone"). while ($i < $num) { $first=mysql_result($result. $database="your_database"."last").$i. mysql_connect(localhost.$i."email").$i. echo "<b>$first $last</b><br>Phone: $phone<br>Mobile: $mobile<br>Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>".following: $first=mysql_result($result. Combining The Script We can now write a full script to output the data. $web=mysql_result($result. $i++. $i=0.$i. $password="password". $phone=mysql_result($result. @mysql_select_db($database) or die( "Unable to select database")."web").$i. $email=mysql_result($result. $result=mysql_query($query). $fax=mysql_result($result.$i."first").$i.$i.$i."email"). $last=mysql_result($result."mobile").

Helvetica. This just gave us a very basic output. } Jan Zumwalt – neatinfo. When you reach a variable position. ?>">Website</a></font></td> </tr> <? $i++. Helvetica.com Pg 46 of 55 rev April 1. ?> in the correct position in your code. include it as follows: <? echo $variablename." ". while ($i < $num) { $first=mysql_result($result. sans-serif"><a href="mailto:<? echo $email. ?></font></td> <td><font face="Arial. ?></font></td> <td><font face="Arial. You can also use the PHP loop to repeat the appropriate code and include it as part of a larger table. ?>">E- mail</a></font></td> <td><font face="Arial.$i.$i."fax").$i. $mobile=mysql_result($result. it would be better if we could format it into a table and display it like this. Formatting Output In the last part of the tutorial we output a list of all the people stored in the database."mobile"). Helvetica. 2010 ."first"). Doing this formatting is not particularly complicated. Helvetica."last"). sans-serif">Name</font></th> <th><font face="Arial. Helvetica."email"). All you need to do is use PHP to output HTML and include your variables in the correct spaces. For example. Instead. Helvetica.More Outputs Throughout this tutorial you have learnt how to create a database and table. In this part I will show you more ways of displaying and outputting the information in the database. Helvetica. ?></font></td> <td><font face="Arial. sans-serif">Phone</font></th> <th><font face="Arial. sans-serif">Mobile</font></th> <th><font face="Arial. Helvetica. $phone=mysql_result($result. though and is not particularly useful for a working website."phone"). using a section of the code from part 4 which looped to output the database you can format it to display it in one large table: <table border="0" cellspacing="2" cellpadding="2"> <tr> <th><font face="Arial. ?></font></td> <td><font face="Arial. Helvetica. sans-serif">Website</font></th> </tr> <? $i=0. sans-serif"><? echo $fax. $fax=mysql_result($result.$i. The easiest way to do this is by closing your PHP tag and entering the HTML normally. Helvetica. Helvetica. $web=mysql_result($result. ?> <tr> <td><font face="Arial. $email=mysql_result($result.$i. sans-serif">Fax</font></th> <th><font face="Arial.$last. sans-serif">E-mail</font></th> <th><font face="Arial. insert information and display the database information. sans-serif"><a href="<? echo $web. Helvetica. sans-serif"><? echo $mobile. sans-serif"><? echo $phone."web"). $last=mysql_result($result. sans-serif"><? echo $first.$i.$i.

or even make changes to the database. Jan Zumwalt – neatinfo. This code will print out table headers. $result=mysql_query($query). Although I won't go int o great depth about it in this section. Selecting Pieces of Data As well as showing the whole database. Always check input data for invalid chanracters and use PHP's built in functions to remove control characters and HTML code etc. Security At this point it should be noted that you must be very careful in using the technique given above. This can occur if the user sets the variable to a value which edits the SQL string being generated in such a way that it can be used for their own purposes. formatting the data as it is output. This security hole is easy to plug with a bit of work. Without correct secuirty measures. it is almost like plain english. then add an extra row for each record in the database.com Pg 47 of 55 rev April 1. ?>">E-mail</a> This shows one of the useful features of using PHP to include MySQL data as you can use it to output parts of your code and make pages fully dynamic. 2010 . if you had a search form you could get the last name people wanted to search for and store it in a variable called $searchlast. To display the whole table we used the query: SELECT * FROM contacts If we just wanted to select ones who had the first name 'John' you would use the following query: SELECT * FROM contacts WHERE first='john' As with other MySQL queries. you can also use variables to give the database criteria. I won't go into full details here. or records which match certian criteria. Again. but there are many websites which give full details (search for 'sql injection attack'). For example. To do this you must use a variation of the SELECT query. As long as you are familiar with PHP and HTML the code is probably pretty self explanatory but I will just point out the last two lines in the table.echo "</table>". for example: <a href="mailto:<? echo $email. there are many websites which go into this in depth. Then you could execute the following piece of code: $query="SELECT * FROM contacts WHERE last='$searchlast'". it would be very easy for someone to access data on your server. In the same way you could select records based on any field in the database. PHP can be used to select individual records. Please note that at the end of the first line there is a ' followed by a " before the semicolon. You can also select ones with more than one field by adding more: field='value' sections onto the query.

but you can also order the output based on a field (for example placing users in alphabetical order). You can sort it on any field. (Ascending order is also for 1-10 etc. Because of this you can make a simple error trap using an IF statement: if ($num==0) { echo "The database contains no contacts yet". Now you have them in order of newest to oldest but this does not restrict the script to only showing the first 5. In this part I will enter into the final aspect of this data displaying. Firstly. An example of this would be to print out only the last 5 records added to a database. This would require them to be in Descending order. it is certainly a possibility. it is quite unlikely that there will be no data. To do this. it has many other uses. but if you allow updating and deleting of records. More Uses Of mysql_numrows and Sorting The value you have assigned to $num is very imiportant as. where $result contains the result of a query on the database (like selecting all the records). By default. For example. you would need to set your loop to run to 5 instead of $num (as this would only run the loop 5 times so only 5 records would be output). To do this you would use the following query: SELECT * FROM contacts ORDER BY last ASC You could also use DESC to order the data in Descending order. Of course. it would be important to check that $num was greater Jan Zumwalt – neatinfo. For those not familiar with standard databases. this will set the value of $num as the number of rows in the result (and it was used in a loop in part 4). selecting one piece of data and stopping errors from happening when you output data. they would need to be placed into order based on the id field (as the one with the latest ID would have been added last. going from 1 upwards. with PHP and MySQL. As I expalined before. Ordering Data Not only can you output data based on the contents of a field. 2010 .com Pg 48 of 55 rev April 1. and descending order provides Z to A and 10-1). a useful sort would be to place all the users in alphabetical order based on their last name. the output from your queries will be in order of the id field. there is an easy way round this using: $num=mysql_numrows($result). apart from error trapping and loops. this would be in Ascending order as it goes from A to Z. Error Trapping By outputting all the information from the database. } else { Output Loop } You can expand on this more by making it more user friendly (for example by providing a link to the Add Data page if no contacts exist).Single Records & Error Trapping In the past two parts of this tutorial I have shown you how to take data out of the database and display it on screen. though. Luckily. before doing this.

than 5. To do this. http://www. if you wanted to have a dynamically generated site run through a database and a single PHP script. using the id field. 2010 . This update link will point to a page allowing the user to update the record. but you can use this very effectively in a number of different ways. This sounds a bit complicated so I will elaborate. you could write the script to include the database data into the design. In the contacts script we are writing.com Pg 49 of 55 rev April 1. This field was set as auto_increment as well as being the primary field. To select the record in this page. I s howed you how to select records from the database based on the contents of partiular fields using: SELECT * FROM contacts WHERE field='value' Now. which in this case would be 7393 Links For Single Records Using this method of choosing a record using the URL to select the record can be expanded further by generating the URL dynamically. For example. I will be showing you how to create an Update page where the user can update the contact details.com/news/items. This may seem to be a little worthless as it is. If there were.php?item=7393 And then have the PHP script look up the record with the id corresponding to $item. you could select each individual page and put it into the output. another column will be included in the output column. Then. I have already explained how this field is unique for every single record in the database. This is easy to do though and the following code is an example of the sort of thing you would want to have: if ($num>5) { $to=5. with an Update link in it. If there were less than 5 rows the loop would run the correct number of times to output the whole database. as if you ran the loop 5 times and there were only 3 rows you would get an error. }else{ $to=$num. we will put: Jan Zumwalt – neatinfo.yoursite. by using the unique ID field we can select any record from our database using: SELECT * FROM contacts WHERE id='$id' Where $id is a variable holding a number of a record. Selecting A Single Record At the end of the last part of this tutorial. you will remember that we included a numerical field called id. } $i=0. the loop would be set to run 5 times. The ID Field If you remember back to creating the database for the contacts at the beginning of this tutorial. but I will now take this a stage further by explaining how this can be used to select an individual record from a database. while ($i < $to) { REST OF CODE This code would check if there were more than 5 rows in the database.g. You can even use the page's URL to specify the record you want e.

there can be code to just select this item. Jan Zumwalt – neatinfo. Then. on the update page. 2010 .?id=$id By getting the id of the record along with the other information when we are outputting the information from the database. this code will create a link which has each record's ID number in it.com Pg 50 of 55 rev April 1.

$fax=mysql_result($result."last"). while ($i < $num) { $first=mysql_result($result. ?>"><br> Last Name: <input type="text" name="ud_last" value="<? echo $last. $last=mysql_result($result. $result=mysql_query($query).$i. ?>"><br> Phone Number: <input type="text" name="ud_phone" value="<? echo $phone. ?>"> First Name: <input type="text" name="ud_first" value="<? echo $first.$i."email"). Space For Code ++$i.$i. $web=mysql_result($result. ?>"><br> Web Address: <input type="text" name="ud_web" value="<? echo $web. just HTML formatting for the output: <form action="updated.$i. $password="password". In this part I will show you how to do the two final actions. mysql_close(). ?>"><br> <input type="Submit" value="Update"> </form> As you can see. } Where 'Space For Code' is in this script is where the code for the update page will go. $database="your_database"."first"). this one already has the current information from the database inserted into it. in fact.$i. $i=0. $email=mysql_result($result.$username."mobile").Updating & Deleting So far you have learnt how to put information into your MySQL database. This makes it much more Jan Zumwalt – neatinfo. this code will output a standard form."phone"). The Update Script Last week I explained how to create a link for each record to point to your update script. Using this you can then create the update script.$i. ?>"><br> E-mail Address: <input type="text" name="ud_email" value="<? echo $email. we connect to the database and select the appropriate record. updating your database and deleting records from it. mysql_connect(localhost. $username="username"."web").com Pg 51 of 55 rev April 1. $num=mysql_numrows($result). 2010 . which will actually have two sections to it. Displaying The Update Page The first part of the update script uses the single record selection from last week but adds a little HTML to it to make it more useful. This is. but instead of having blank boxes like on the form for inserting a new record. By using the $id variable you output links which would pass the correct ID to the script so that it can update the database. ?>"><br> Mobile Number: <input type="text" name="ud_mobile" value="<? echo $mobile. $id=$_GET['id']. First of all. view the information in it and select which information you would like to view. $phone=mysql_result($result.$i. ?>"><br> Fax Number: <input type="text" name="ud_fax" value="<? echo $fax. $mobile=mysql_result($result.php" method="post"> <input type="hidden" name="ud_id" value="<? echo $id. $query=" SELECT * FROM contacts WHERE id='$id'".$password)."fax").

fax='$ud_fax'. Deleting Records The final part of the contacts database which needs to be created is a page to delete records. $database="your_database". web='$ud_web' WHERE id='$ud_id'". web = '$ud_web' WHERE id = '$ud_id'". Loops At this time it seems appropriate to mention another use of loops with a database. Instead of the UPDATE query you should use: DELETE FROM contacts WHERE id='$id' This would then be used with the connection and confirmation code as above.$password). This code would update the database and give the user a confirmation.smith. last = '$ud_last'. $ud_last=$_POST['ud_last']. For example. phone='$ud_phone'. email='$ud_email'.$username. you can also use loops to execute queries. $ud_web=$_POST['ud_web']. As with the Update page. This query tells the database to update the contacts table where the ID is the same as the value stored in $ud_id (which as you can see from the form on the previous page was set as the id of the record we are updating) and to set the following fields to the specified values (which were set using the form on the previous page). $ud_fax=$_POST['ud_fax']. mobile='$ud_mobile'.com Pg 52 of 55 rev April 1.effective for an update script. except with a slightly different MySQL query. this should have a record ID sent to it in the URL e. email = '$ud_email'. $password="password". $ud_first=$_POST['ud_first']. fax = '$ud_fax'. mobile = '$ud_mobile'.php?id=9 The code to do this is the same as to update the database. mysql_query($query). $username="username". last='$ud_last'. if you wanted to change all the records in the database with the last name Smith to have the website www. mysql_close(). $ud_phone=$_POST['ud_phone'].com: Jan Zumwalt – neatinfo. As well as using a loop to get information from a database as we have before. $ud_email=$_POST['ud_email']. mysql_connect(localhost. $ud_mobile=$_POST['ud_mobile'].g. Updating The Database The next stage of this script is to actually update the database. This query could then be integrated into a simple script: $ud_id=$_POST['ud_id']. $query="UPDATE contacts SET first='$ud_first'. echo "Record Updated". This is a simple operation and just involves a new query for the database: $query = "UPDATE contacts SET first = '$ud_first'. phone = '$ud_phone'. 2010 .: delete.

$i=0. and no loop. mysql_query($query). this could have been achived far easier and quicker using: $query1="UPDATE contacts SET web='http://www. Jan Zumwalt – neatinfo.smith."id").com' WHERE last='Smith'".com Pg 53 of 55 rev April 1. Of course. 2010 . Standard Database Connection Code $query=" SELECT * FROM contacts WHERE last='Smith'". $num=mysql_numrows($result).$i. } mysql_close().com' WHERE id='$id'". ++$i.smith. while ($i < $num) { $id=mysql_result($result. $query1="UPDATE contacts SET web='http://www. $result=mysql_query($query).

$password="databasepassword". there is only one file to change. you can leave out one of the % signs so that you can specify the position of the string e.php"). Also. You can use the same principal to connect to the database.: LIKE 'piano%' Jan Zumwalt – neatinfo. Then. LIKE tells the database to perform its 'searching' feature. at the beginning. Because of this. Saving Time When creating complex scripts using databases you will find that the most common thing you are doing is connecting to a database. In this part I will show you some final MySQL tips and will give you a final version of the script. For example for a username/password file you would create a file called: dbinfo.g. by putting the connection code in the file.inc.inc. This is by using the LIKE function as follows: SELECT * FROM tablename WHERE fieldname LIKE '%$string%' To explain furhter. The % signs mean that any other data could appear in their place and $string would hold your search string.: LIKE '%piano%' which would output any rows with piano in the specified field. 2010 . ?> Replacing the appropriate sections.Finishing The Script Throughout this tutorial I have taught you how to use PHP to interact with a MySQL (or SQL) database and how to use the most common commands available.inc. Then in your php files use the following code: include("dbinfo. $password and $database throughout your scripts without having to define them every time. $database="databasename". throughout this tutorial. if you ever change this information.php"). you can actually save time by creating either a username/password file or a connection file. also shown you how to create a basic contacts management system to illustrate some of the options you can use. you can use the variables $username. I have.php and put the following in it: <? $username="databaseusername".com Pg 54 of 55 rev April 1. but you must always be sure to close the connection in each file or you may have problems with your MySQL server. Similarly. Searching A limited form of searching can also be performed on your database using a built in MySQL function. for example if you move to another web host. or include("/full/path/to/file/dbinfo. In this place could be a word or number as well e.g.

2010 .com Pg 55 of 55 rev April 1. Using databases with the web opens up a huge new selection of things you can do and can make a simple website much more powerful. Would not show up. The Finished Script Throughout this tutorial I have given you pieces of code to make a contacts database script. allowing user interaction and feedback and much more. Conclusion From this tutorial you should now know the basics of using PHP and MySQL together to create database-enabled websites and programs.Will only output rows where the specified field begins with piano. saving time updating the site. so: The piano is next to the table. You can download the full script as a zip file so that you can examine the code (see Related Links). Jan Zumwalt – neatinfo.