PHP Cheat Sheet
PHP Cheat Sheet
PHP Cheat Sheet
dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Using Echo()</title> </head> <body> <p>This is standard HTML.</p> <?php echo 'This was generated using PHP!'; ?> </body> </html> Example 2: comments.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Comments</title> </head> <body> <?php # Created March 7, 2010 # Created by <write your name here> # This script does nothing much. echo '<p>This is a line of text.<br />This is another line of text.</p>'; /* echo 'This line will not be executed.'; */ echo "<p>Now I'm done.</p>"; // End of PHP code. ?> </body> </html> Example 3: predefined.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Predefined Variables</title>
</head> <body> <?php // Create a shorthand version of the variable names: $file = $_SERVER['SCRIPT_FILENAME']; $user = $_SERVER['HTTP_USER_AGENT']; $server = $_SERVER['SERVER_SOFTWARE']; // Print the name of this script: echo "<p>You are running the file:<br /><b>$file</b>.</p>\n"; // Print the user's information: echo "<p>You are viewing this page using:<br /><b>$user</b></p>\n"; // Print the server's information: echo "<p>This server is running:<br /><b>$server</b>.</p>\n"; ?> </body> </html> Exercise 4: constants.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Constants</title> </head> <body> <?php // Set today's date as a constant: define ('TODAY', 'August 28, 2007'); // Print a message, using predefined constants and the TODAY constant: echo '<p>Today is ' . TODAY . '.<br />This server is running version <b>' . PHP_VERSION . '</b> of PHP on the <b>' . PHP_OS . '</b> operating system.</p>'; ?> </body> </html> Exercise 5: strings.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Strings</title> </head> <body> <?php
// Create the variables: $first_name = 'Haruki'; $last_name = 'Murakami'; $book = 'Kafka on the Shore'; //Print the values: echo "<p>The book <em>$book</em> was written by $first_name $last_name.</p>"; ?> </body> </html> Exercise 6: calendar.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Calendar</title> </head> <body> <form action="calendar.php" method="post"> <?php // This script makes three pull-down menus // for an HTML form: months, days, years. // Make the months array: $months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Make the days and years arrays: $days = range (1, 31); $years = range (2008, 2018); // Make the months pull-down menu: echo '<select name="month">'; foreach ($months as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // Make the days pull-down menu: echo '<select name="day">'; foreach ($days as $value) { echo "<option value=\"$value\">$value</option>\n"; } echo '</select>'; // Make the years pull-down menu: echo '<select name="year">'; foreach ($years as $value) { echo "<option value=\"$value\">$value</option>\n"; } echo '</select>'; ?>
</form> </body> </html> Example 7: multi.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Multidimensional Arrays</title> </head> <body> <p>Some North American States, Provinces, and Territories:</p> <?php // Create one array: $mexico = array( 'YU' => 'Yucatan', 'BC' => 'Baja California', 'OA' => 'Oaxaca' ); // Create another array: $us = array ( 'MD' => 'Maryland', 'IL' => 'Illinois', 'PA' => 'Pennsylvania', 'IA' => 'Iowa' ); // Create a third array: $canada = array ( 'QC' => 'Quebec', 'AB' => 'Alberta', 'NT' => 'Northwest Territories', 'YT' => 'Yukon', 'PE' => 'Prince Edward Island' ); // Combine the arrays: $n_america = array( 'Mexico' => $mexico, 'United States' => $us, 'Canada' => $canada ); // Loop through the countries: foreach ($n_america as $country => $list) { // Print a heading: echo "<h2>$country</h2><ul>"; // Print each state, province, or territory: foreach ($list as $k => $v) { echo "<li>$k - $v</li>\n"; }
// Close the list: echo '</ul>'; } // End of main FOREACH. ?> </body> </html> Example 8: numbers.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Numbers</title> </head> <body> <?php // Set the variables: $quantity = 30; // Buying 30 widgets. $price = 119.95; $taxrate = .05; // 5% sales tax. // Calculate the total: $total = $quantity * $price; $total = $total + ($total * $taxrate); // Calculate and add the tax. // Format the total: $total = number_format ($total, 2); // Print the results: echo '<p>You are purchasing <b>' . $quantity . '</b> widget(s) at a cost of <b>$' . $price . '</b> each. With tax, the total comes to <b>$' . $total . '</b>.</p>'; ?> </body> </html> Example 9: conditional-operator.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Conditional Operator</title> </head> <body> <?php //Assign value: $BlackjackPlayer1 = 20;
//Conditional operator: ($BlackjackPlayer1 <= 21) ? $Result = Player 1 is still in the game. : $Result = Player 1 is out of the action.; //Display result: echo "<p>$Result</p>"; ?> </body> </html> Example 10: if-statement.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>If Statement</title> </head> <body> <?php $ExampleVar = 5; if ($ExampleVar == 5) { // CONDITION EVALUATES TO 'TRUE' echo <p>The condition evaluates to true.</p>; echo '<p>$ExampleVar is equal to ', $ExampleVar.</p>; echo <p>Each of these lines will be printed.</p>; } echo <p>This statement always executes after the if statement.</p>; ?> </body> </html> Example 11: while-loop.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>While Loop</title> </head> <body> <?php //First Loop $Count = 1; while ($Count <= 5) { echo $Count<br />; ++$Count; } echo <p>You have printed 5 numbers.</p>;
//using decrement $Count = 10; while ($Count > 0) { echo $Count<br />; --$Count; } echo <p>We have liftoff.</p>; //Using *= operator $Count = 1; while ($Count <= 100) { echo $Count<br />; $Count *= 2; } ?> </body> </html> Example 12: calendar.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Calendar</title> </head> <body> <form action="calendar.php" method="post"> <?php // This script makes three pull-down menus // for an HTML form: months, days, years. // Make the months array: $months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Make the months pull-down menu: echo '<select name="month">'; foreach ($months as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // Make the days pull-down menu: echo '<select name="day">'; for ($day = 1; $day <= 31; $day++) { echo "<option value=\"$day\">$day</option>\n"; } echo '</select>'; // Make the years pull-down menu: echo '<select name="year">'; for ($year = 2008; $year <= 2018; $year++) { echo "<option value=\"$year\">$year</option>\n"; }
echo '</select>'; ?> </form> </body> </html> Example 13: simple-function.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Simple Function</title> </head> <body> <?php function printCompanyName($CompanyName) { echo <p>$CompanyName</p>; } printCompanyName(Course Technology); ?> </form> </body> </html> Example 14: global-variables.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Global Variables</title> </head> <body> <?php //Local variable $life = 42; function meaningOfLife1() { print "The meaning of life is $life<br />"; } meaningOfLife1(); //global variable $life = 42; function meaningOfLife2() { global $life; print "The meaning of life is $life<br />"; } meaningOfLife2();
$life = 42; function meaningOfLife3() { print "The meaning of life is $_GLOBALS["$life"]<br />"; } meaningOfLife3(); ?> </form> </body> </html> Example 15: form.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Simple HTML Form</title> </head> <body> <form action="handle_form.php" method="post"> <fieldset><legend>Enter your information in the form below:</legend> /></p> <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40"
<p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p> <p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p><b>Age:</b> <select name="age"> <option value="0-29">Under 30</option> <option value="30-60">Between 30 and 60</option> <option value="60+">Over 60</option> </select></p> <p><b>Comments:</b> <textarea name="comments" rows="3" cols="40"></textarea></p> </fieldset> <div align="center"><input type="submit" name="submit" value="Submit My Information" /></div> </form> </body> </html> Example 16: handle-form.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Form Feedback</title> <style type="text/css" title="text/css" media="all"> .error { font-weight: bold; color: #C00; } </style> </head> <body> <?php // Print the submitted information: if ( !empty($_POST['name']) && !empty($_POST['comments']) && ! empty($_POST['email']) ) { echo "<p>Thank you, <b>{$_POST['name']}</b>, for the following comments:<br /> <tt>{$_POST['comments']}</tt></p> <p>We will reply to you at <i>{$_POST['email']}</i>.</p>\n"; } else { // Missing form value. echo '<p class="error">Please go back and fill out the form again.</p>'; } ?> </body> </html> Example 17: validate-form.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Form Feedback</title> <style type="text/css" title="text/css" media="all"> .error { font-weight: bold; color: #C00; } </style> </head> <body> <?php // Validate the name: if (!empty($_REQUEST['name'])) { $name = $_REQUEST['name']; } else { $name = NULL; echo '<p class="error">You forgot to enter your name!</p>'; } // Validate the email: if (!empty($_REQUEST['email'])) {
$email = $_REQUEST['email']; } else { $email = NULL; echo '<p class="error">You forgot to enter your email address!</p>'; } // Validate the comments: if (!empty($_REQUEST['comments'])) { $comments = $_REQUEST['comments']; } else { $comments = NULL; echo '<p class="error">You forgot to enter your comments!</p>'; } // Validate the gender: if (isset($_REQUEST['gender'])) { $gender = $_REQUEST['gender']; if ($gender == 'M') { echo '<p><b>Good day, Sir!</b></p>'; } elseif ($gender == 'F') { echo '<p><b>Good day, Madam!</b></p>'; } else { // Unacceptable value. $gender = NULL; echo '<p class="error">Gender should be either "M" or "F"!</p>'; } } else { // $_REQUEST['gender'] is not set. $gender = NULL; echo '<p class="error">You forgot to select your gender!</p>'; } // If everything is OK, print the message: if ($name && $email && $gender && $comments) { echo "<p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p>We will reply to you at <i>$email</i>.</p>\n"; } else { // Missing form value. echo '<p class="error">Please go back and fill out the form again.</p>'; } ?> </body> </html> Example 18: header.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $page_title; ?></title> <link rel="stylesheet" href="includes/style.css" type="text/css" media="screen" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head> <body> <div id="header"> <h1>Your Website</h1> <h2>catchy slogan...</h2> </div> <div id="navigation"> <ul> <li><a href="index.php">Home Page</a></li> <li><a href="calculator.php">Calculator</a></li> <li><a href="dateform.php">Date Form</a></li> <li><a href="#">link four</a></li> <li><a href="#">link five</a></li> </ul> </div> <div id="content"><!-- Start of the page-specific content. --> <!-- header.html --> Example 19: footer.html <!-- - footer.html --> <!-- End of the page-specific content. --></div> <div id="footer"> <p>Copyright © <a href="#">Plain and Simple</a> 2007 | Designed by <a href="http://www.edg3.co.uk/">edg3.co.uk</a> | Sponsored by <a href="http://www.opendesigns.org/">Open Designs</a> | Valid <a href="http://jigsaw.w3.org/css-validator/">CSS</a> & <a href="http://validator.w3.org/">XHTML</a></p> </div> </body> </html> Example 20: include.php <?php $page_title = 'Welcome to this Site!'; include ('includes/header.html'); ?> <h1>Content Header</h1> <p>This is where the page-specific content goes. This section, and the corresponding header, will change from one page to the next.</p> <?php include ('includes/footer.html'); ?>
Example 21: write-file.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Writing to a file</title> </head> <body> <?php //Set variables $TournamentBowlers = Blair, Dennis\n; $TournamentBowlers .= Hernandez, Louis\n; $TournamentBowlers .= Miller, Erica\n; $TournamentBowlers .= Morinaga, Scott\n; $TournamentBowlers .= Picard, Raymond\n; $BowlersFile = bowlers.txt; //write to file file_put_contents($BowlersFile, $TournamentBowlers); //status message if (file_put_contents($BowlersFile, $TournamentBowlers) > 0) echo <p>Data was successfully written to the $BowlersFile file.</p>; else echo <p>No data was written to the $BowlersFile file.</p>; ?> </body> </html> Example 22: registration-form-file.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Writing to a file</title> </head> <body> <?php <h1>Registration Form</h1> <?php //Check for form submission if (isset($_GET['first_name']) && isset($_GET['last_name'])) { $BowlerFirst = $_GET['first_name']; $BowlerLast = $_GET['last_name']; $NewBowler = $BowlerLast . , . $BowlerFirst . \n; $BowlersFile = bowlers.txt; //Write to file if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo <p>{$_GET['first_name']} {$_GET['last_name']} has been registered for the bowling tournament!</p>; else echo <p>Registration error!</p>;
} else
//error messages echo <p>To sign up for the bowling tournament, enter your first and last name and click the Register button.</p>; ?> <form action=registration-form-file.php method=get enctype=application/x-www-form-urlencoded> <p>First Name: <input type=text name=first_name size=30 /></p> <p>Last Name: <input type=text name=last_name size=30 /></p> <p><input type=submit value=Register /></p> </form> </body> </html> Example 23: registration-form-file-2.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Writing to a file</title> </head> <body> <?php <h1>Registration Form</h1> <?php //Check for form submission if (isset($_GET['first_name']) && isset($_GET['last_name'])) { $BowlerFirst = addslashes($_GET['first_name']); $BowlerLast = addslashes($_GET['last_name']); $NewBowler = $BowlerLast . , . $BowlerFirst . \n; $BowlersFile = bowlers.txt; if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo <p> . stripslashes($_GET['first_name']). . stripslashes($_GET['last_name']). has been registered for the bowling tournament! </p>; else } else echo <p>Registration error!</p>;
echo <p>To sign up for the bowling tournament, enter your first and last name and click the Register button.</p>;} ?> <form action=registration-form-file-2.php method=get enctype=application/x-www-form-urlencoded> <p>First Name: <input type=text name=first_name size=30 /></p> <p>Last Name: <input type=text name=last_name size=30 /></p> <p><input type=submit value=Register /></p> </form> </body>
</html> Example 24: slashes.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Addslashes & Stripslashes</title> </head> <body> <?php <h1>Registration Form</h1> <?php //Check for form submission if (isset($_GET['first_name']) && isset($_GET['last_name'])) { $BowlerFirst = addslashes($_GET['first_name']); $BowlerLast = addslashes($_GET['last_name']); $NewBowler = $BowlerLast . , . $BowlerFirst . \n; $BowlersFile = bowlers.txt; if (file_put_contents($BowlersFile, $NewBowler, FILE_APPEND) > 0) echo <p> . stripslashes($_GET['first_name']). . stripslashes($_GET['last_name']). has been registered for the bowling tournament! </p>; else } else echo <p>Registration error!</p>;
echo <p>To sign up for the bowling tournament, enter your first and last name and click the Register button.</p>;} ?> <form action=slashes.php method=get enctype=application/x-www-form-urlencoded> <p>First Name: <input type=text name=first_name size=30 /></p> <p>Last Name: <input type=text name=last_name size=30 /></p> <p><input type=submit value=Register /></p> </form> </body> </html> Example 25: file-to-array.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Putting File contents into an Array</title> </head> <body>
<?php $January = 48, 42, 68\n; $January .= 48, 42, 69\n; $January .= 49, 42, 69\n; $January .= 49, 42, 61\n; $January .= 49, 42, 65\n; $January .= 49, 42, 62\n; $January .= 49, 42, 62\n; file_put_contents(sfjanaverages.txt, $January); $JanuaryTemps = file(sfjanaverages.txt); for ($i=0; $i<count($JanuaryTemps); ++$i) { $CurDay = explode(, , $JanuaryTemps[$i]); echo <p><strong>Day . ($i + 1) . </strong><br />; echo High: {$CurDay[0]}<br />; echo Low: {$CurDay[1]}<br />; echo Mean: {$CurDay[2]}</p>; } <form action=registration-form-file-2.php method=get enctype=application/x-www-form-urlencoded> <p>First Name: <input type=text name=first_name size=30 /></p> <p>Last Name: <input type=text name=last_name size=30 /></p> <p><input type=submit value=Register /></p> </form> </body> </html> Example 26: database1.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Connecting to a database</title> </head> <body> <?php $user = administrator"; $pass = password"; $db = contacts"; $link = @mysqli_connect( "localhost", $user, $pass ); if (!$link) { die("Couldn't connect to MySQL: ".mysql_error()); } print "<h2>Successfully connected to server</h2>\n\n"; or die ( "Couldn't open $db: ".mysqli_error() ); print "Successfully selected database \"$db\"<br />\n"; mysqli_close( $link ); ?> </body>
</html> Example 27: retrieve.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Retrieving data</title> </head> <body> <?php $user = administrator"; $pass = password"; $db = contacts"; $link = @mysqli_connect( "localhost", $user, $pass ); if (!$link) { die("Couldn't connect to MySQL: ".mysql_error()); } print "<h2>Successfully connected to server</h2>\n\n"; or die ( "Couldn't open $db: ".mysqli_error() ); print "Successfully selected database \"$db\"<br />\n"; $result = @mysqli_query( "SELECT firstname, lastname FROM address_book ); $num_rows = mysqli_num_rows( $result ); print "<p>$num_rows have added data to the table</p>\n"; print "<table border=\"1\">\n"; while ( $a_row = mysqli_fetch_row( $result ) ) { print "<tr>\n"; foreach ( $a_row as $field ) { print "\t<td>".$field."</td>\n"; } print "</tr>\n"; } print "</table>\n"; mysqli_close( $link ); ?> </body> </html> Example 28: insert.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Inserting data data</title> </head> <body>
<?php $user = administrator"; $pass = password"; $db = contacts"; $link = @mysqli_connect( "localhost", $user, $pass ); if (!$link) { die("Couldn't connect to MySQL: ".mysql_error()); } print "<h2>Successfully connected to server</h2>\n\n"; or die ( "Couldn't open $db: ".mysqli_error() ); print "Successfully selected database \"$db\"<br />\n"; $query = "INSERT INTO address_book( first_name, last_name, address, phone, email ) values( Regnard', Raquedan', Quezon City, ,09192907711, [email protected]' )"; print "running query: <br />\n$query<br />\n"; mysqli_query( $query, $link ) or die ( "INSERT error: ".mysql_error() ); $result = @mysqli_query( "SELECT firstname, lastname FROM address_book ); $num_rows = mysqli_num_rows( $result ); print "<p>$num_rows have added data to the table</p>\n"; print "<table border=\"1\">\n"; while ( $a_row = mysqli_fetch_row( $result ) ) { print "<tr>\n"; foreach ( $a_row as $field ) { print "\t<td>".$field."</td>\n"; } print "</tr>\n"; } print "</table>\n"; mysqli_close( $link ); ?> </body> </html> Example 29: update.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Updating data data</title> </head> <body> <?php $user = administrator"; $pass = password"; $db = contacts";
$link = @mysqli_connect( "localhost", $user, $pass ); if (!$link) { die("Couldn't connect to MySQL: ".mysql_error()); } print "<h2>Successfully connected to server</h2>\n\n"; or die ( "Couldn't open $db: ".mysqli_error() ); print "Successfully selected database \"$db\"<br />\n"; $query = mysqli_query( "UPDATE address_book SET address =Makati' WHERE id=1 ); If ($query == TRUE) { print Updated: .mysqli_affected_rows(); } else { print Update cannot be performed; } $result = @mysqli_query( "SELECT firstname, lastname FROM address_book ); $num_rows = mysqli_num_rows( $result ); print "<table border=\"1\">\n"; while ( $a_row = mysqli_fetch_row( $result ) ) { print "<tr>\n"; foreach ( $a_row as $field ) { print "\t<td>".$field."</td>\n"; } print "</tr>\n"; } print "</table>\n"; mysqli_close( $link ); ?> </body> </html> Example 30: delete.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Inserting data data</title> </head> <body> <?php $user = administrator"; $pass = password"; $db = contacts"; $link = @mysqli_connect( "localhost", $user, $pass ); if (!$link) { die("Couldn't connect to MySQL: ".mysql_error()); } print "<h2>Successfully connected to server</h2>\n\n"; or die ( "Couldn't open $db: ".mysqli_error() ); print "Successfully selected database \"$db\"<br />\n"; $query = mysqli_query( "DELETE FROM address_book WHERE address=Makati);
If ($query == TRUE) { print Updated: .mysqli_affected_rows(); } else { print Deletion cannot be performed; } $result = @mysqli_query( "SELECT firstname, lastname FROM address_book ); $num_rows = mysqli_num_rows( $result ); print "<table border=\"1\">\n"; while ( $a_row = mysqli_fetch_row( $result ) ) { print "<tr>\n"; foreach ( $a_row as $field ) { print "\t<td>".$field."</td>\n"; } print "</tr>\n"; } print "</table>\n"; mysqli_close( $link ); ?> </body> </html> Example 31: cookies.php <?php setcookie( "vegetable", "artichoke", time()+3600, "/"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Setting and Printing a Cookie Value</title> </head> <body> <?php if ( isset( $_COOKIE['vegetable'] ) ) { print "<p>Hello again, your chosen vegetable is "; print "{$_COOKIE['vegetable']}</p>"; } else { print "<p>Hello you. This may be your first visit</p>"; } setcookie("firstName", "Don"); setcookie("lastName", "Gosselin"); setcookie("occupation", "writer"); if (isset($_COOKIE['firstName']) && isset($_COOKIE['lastName']) && isset($_COOKIE['occupation'])) echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']} is a {$_COOKIE['occupation']}."; setcookie("professional[0]", "Don"); setcookie("professional[1]", "Gosselin"); setcookie("professional[2]", "writer"); if (isset($_COOKIE['professional']))
echo "{$_COOKIE['professional'][0]} {$_COOKIE['professional'][1]} is a {$_COOKIE['professional'][2]}."; ?> </body> </html> Example 32: sessions.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Sessions</title> </head> <body> <?php session_start(); if (isset($_SESSION['firstName']) && isset($_SESSION['lastName']) && isset($_SESSION['occupation'])) echo "<p>" . $_SESSION['firstName'] . " " . $_SESSION['lastName'] . " is a " . $_SESSION['occupation'] . "</p>"; ?> </body> </html>