Presentation is loading. Please wait.

Presentation is loading. Please wait.

Paul Jacobs The iSchool University of Maryland Thursday, Oct. 12, 2017

Similar presentations


Presentation on theme: "Paul Jacobs The iSchool University of Maryland Thursday, Oct. 12, 2017"— Presentation transcript:

1 Paul Jacobs The iSchool University of Maryland Thursday, Oct. 12, 2017
INFM 603: Session 7 Introduction to Server-Side Scripts Using PHP Paul Jacobs The iSchool University of Maryland Thursday, Oct. 12, 2017 This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States See for details

2 Today’s Topics Introduction to Server-side Scripting
Programming Using PHP: Dynamically Generating HTML on the Server for Display on the Client Integrating PHP with Forms Integrating PHP with Databases

3 Goals for PHP Session Revisit and understand the role of server-side scripts in web-based applications Understand how to integrate PHP with XHTML Embedding PHP code into HTML Generating HTML from PHP to display on the client Using variables and other constructs Understand how to use XHTML forms with PHP The HTTP “post” action Getting values from form input Displaying resulting XHTML Understand how to integrate with MySQL – Accessing and updating databases Intro to Scripting Using PHP PHP and Forms PHP and Databases

4 Why Server-Side Scripts?
“We” meaning app. developers, have control over the environment (software installed, data, security, etc.) – not dependent on clients/users Scripts can access a huge range of data and applications that may be inaccessible to clients directly – control the interface Many different scripting languages are available (PHP, Ruby, Perl/Python, Java, . . .) depending on needs, programming resources Intro to Scripting Using PHP PHP and Forms PHP and Databases

5 Why PHP (Hypertext Preprocessor)?
Part of the well-integrated “LAMP” stack (Linux, Apache, MySQL, PHP) – powerful, but easy to acquire and use – free Great as a teaching tool Like other parts of this course, a “gateway” to other scripting languages that can be used Intro to Scripting Using PHP PHP and Forms PHP and Databases

6 Our First PHP Program <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" " <html> <head> <meta content="text/html; charset=ISO " http-equiv="content-type"> <title>Simple Test PHP Script</title> </head> <?php echo '<p>PHP is running on the server!</p>'; ?> </html> PHP scripts are marked by these <?php … ?> tags and browsers ignore what is between Intro to Scripting Using PHP PHP and Forms PHP and Databases

7 PHP “Hello World” Display
The output of the PHP script is HTML, which is then displayed as HTML on the client browser Intro to Scripting Using PHP PHP and Forms PHP and Databases

8 Some Basic PHP PHP Variables – marked by $, e.g.
$txt = "Hello world!"; $x = 5; $y = 10.5; PHP Output – echo and print – slight differences, but output HTML, e.g. echo “<p>Hello World</p>”; print “<h1>PHP is running</h1>”; echo “<p>The value of $y is greater than the value of $x</p>”; // note that variables inside of quotes are treated as variables! print $x + $y; PHP Operators – very similar to JavaScript, e.g. +, *, /, arithmetic ++, increment and decrement >, <, ==, >=, <= , != - comparison =, +=, *=, - assignment Intro to Scripting Using PHP PHP and Forms PHP and Databases

9 Some Basic PHP Control Structures
PHP Conditional – if … then … else (similar to JavaScript), e.g. $t = date("H"); if ($t < "20") {     echo "Have a good day!"; } else {     echo "Have a good night!"; } PHP while loop: while($x <= 5) {     echo "The number is: $x <br>";     $x++; } PHP for loop: for ($x = 0; $x <= 10; $x++) {     echo "The number is: $x <br>"; } Intro to Scripting Using PHP PHP and Forms PHP and Databases

10 PHP Functions function sum($x, $y) { $z = $x + $y; return $z;
} // this is a comment $n1 = 2; $n2 = 4; $sumval = sum($n1, $n2); echo “<p>The sum of $n1 and $n2 is $sumval</p>”; Intro to Scripting Using PHP PHP and Forms PHP and Databases

11 PHP and Forms – HTML Form
<p> Enter a number</p> <form action=“mytest.php" method="post"> <input type="text" name="value"><br> <input type="submit"> </form> Very important! This PHP script (from a separate file) runs when the user hits the “submit” button. If the form is on the server, this names the PHP file in the same place on the server. Otherwise, this names the whole URL of the PHP script Very important! The name of the form element (can be anything, but in this case “value”) becomes the name of the variable in the post Intro to Scripting Using PHP PHP and Forms PHP and Databases

12 PHP and Forms – PHP Script (mytest.php, gets input from POST)
$fnum = $_POST['value']; $res = sqrt($fnum); echo "<p>The square root of $fnum is $res</p>"; ?> Very important! The name of the form element (can be anything, but in this case “value”) is extracted from the POST and assigned to a PHP variable (in this case $fnum). Be careful; don’t just assume that PHP variables will have the names you think they should have. Intro to Scripting Using PHP PHP and Forms PHP and Databases

13 Practice First write “Hello World” (or something similar) – save it as a .php file and upload to your virtual server (youruserid.psjconsulting.com) After that works, create a file runfact.html that takes a number as input from the user and posts to runfact.php. Create a file runfact.php that gets the value from the post, computes the factorial, and prints it. Upload both to your virtual server (not to terpconnect). Actually the html file doesn’t have to be uploaded if you use the full URL of the php file. Test to see if your programs work

14 Connecting to MySQL Using PHP

15 PHP and MySQL – Basic Needs
Open and check a connection to a MySQL database Old: // Create connection $conn = mysql_connect($servername, $username, $password); // Check connection if (!$conn) {     die("Connection failed: " . mysqli_connect_error()); } New (object-oriented) // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) {     die("Connection failed: " . $conn->connect_error); } Interim // Create connection $conn = mysqli_connect($servername, $username, $password); etc. Intro to Scripting Using PHP PHP and Forms PHP and Databases

16 PHP and MySQL – Basic Needs (cont’d)
Run a query on the [open] database and process results (object-oriented) $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) {     // output data of each row     while($row = $result->fetch_assoc()) {         echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";     } } else {     echo "0 results"; } $conn->close(); // close the connection Intro to Scripting Using PHP PHP and Forms PHP and Databases

17 Notice: Some of the examples in this section were originally copied from
© Deitel, Internet and World Wide Web: How to Program, Prentice Hall 2004 …and have been updated Intro to Scripting Using PHP PHP and Forms PHP and Databases

18 PHP – MySQL – Mailing List Example
extract( $_POST ); // not used // build SELECT query $query = "SELECT * FROM contacts"; // Connect to MySQL $database = new mysqli("localhost", "testuser1", "*********", "testuser1_inclassdemo"); // Check connection if ($database->connect_error) { die("Connection failed: " . $database->connect_error); // query database if ( !( $result = $database->query( $query) ) ) { print( "Could not execute query! <br />" ); die(“Terminating”); } ?> Connect to MySQL on server (localhost); always check that this worked Notice $database is now a variable used for the open database Just execute the query stored in $query; save the result in $result Intro to Scripting Using PHP PHP and Forms PHP and Databases

19 PHP – MySQL (cont’d) <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> <tr> <td>ID</td> <td>Last Name</td> <td>First Name</td> <td> Address</td> <td>Phone Number</td> <td>Book</td> <td>Operating System</td> </tr> <?php // fetch each record in result set for ( $counter = 0; $row = $result->fetch_row(); $counter++ ){ // build table to display results print( "<tr>" ); foreach ( $row as $key => $value ) print( "<td>$value</td>" ); print( "</tr>" ); } $database->close(); ?> </table> This PHP code is in the middle of an HTML table to fill in the table Intro to Scripting Using PHP PHP and Forms PHP and Databases It’s always a good idea to close the connection

20 PHP – MySQL – Pet Form Example
<head> <title>Sample form to enter pet info</title> </head> <body> <h1>Please tell us about your pets.</h1> Please fill in all fields and click "Submit". <!-- post form data to form.php --> <form method = "post" action = "petupdate.php" > <p><img src = "images/OwnerInfo.png" alt = "User" width="400" height="100" /> </p> <table width="774" height="154" border="1"> <caption> <strong> Contact information </strong> </caption> <tr> <td width="217" height="47"><img src="images/pn-a1.png" width="160" height="30" /></td> <td width="671"><input type = "text" name = "petname" size = 100/></td> </tr> <td><img src="images/pn-a2.png" width="160" height="30" /></td> <td><input type = "text" name = "ownername" size = "100"/></td> This HTML form will post data to “petupdate.php” on the server when the submit occurs Intro to Scripting Using PHP PHP and Forms PHP and Databases

21 PHP – MySQL – Pet Form Example (cont’d)
<tr> <td><img src="images/pn-a3.png" width="160" height="30" /></td> <td><input type = "text" name = "ownertelno" size = "100"/></td> </tr> <td><img src="images/pn-a4.png" width="160" height="30" /></td> <td><input type = "text" name = "owner " size = "100"/></td> </table> <p><span style = "color: blue"> </span> <br /> <img src = "images/PetInfo.png" alt = "Pet Information" width="400" height="100" /><br /> <span style = "color: blue"> What is your pet's breed? </span><br /> <!-- create drop-down list containing book names --> <select name = "petbreed"> <option>American Shorthair</option> <option>Siamese</option> <option>Maine Coon Cat</option> <option>Other</option> </select> <br /> Get rest of owner info and pet breed from form Intro to Scripting Using PHP PHP and Forms PHP and Databases

22 PHP – MySQL – Pet Form Example (cont’d)
<!-- create five radio buttons --> <input type = "radio" name = "petfood" value = "Meow Mix" checked = "checked" /> Meow Mix <input type = "radio" name = "petfood" value = "Purina" /> Purina "Science Diet CD" /> Science Diet C/D <br /> <input type = "radio" name = "petfood" value = "Iams" /> Iam's <input type = "radio" name = "petfood" value = "Other" /> Other<br /> <!-- create a submit button --> <input type = "submit" value = "Submit" /> </p> </form> </body> </html> Get pet food info using radio buttons and make submit button Intro to Scripting Using PHP PHP and Forms PHP and Databases

23 PHP – MySQL – Pet Form Example – Form Page
Intro to Scripting Using PHP PHP and Forms PHP and Databases

24 PHP – MySQL – Pet Form Example – PHP Code
When posting to PHP, you usually just get all the variable data from the form <?php extract ( $_POST ); ?> <!-- petupdate.php > <!-- Read information sent from input form --> <html xmlns = " <head> <title>Pet Form Validation and Database Update</title> </head> <body style = "font-family: arial,sans-serif"> <p>Hi <span style = "color: blue"> <strong> <?php print( "$petname" ); ?>'s owner </strong> </span>. Thank you for telling us about <?php print ("$petname"); ?> .<br /> He/she has been added to the <?php print( "$petbreed " ); ?> </span> database. </p> Intro to Scripting Using PHP PHP and Forms PHP and Databases

25 PHP – MySQL – Pet Form Example – PHP Code (cont’d)
<strong>The following information has been saved in our database:</strong><br /> <table width="639" height="66" border = "0" cellpadding = "0" cellspacing = "10"> <tr> <td width="73" bgcolor = "#ffffaa">Name </td> <td width="72" bgcolor = "#ffffbb">Owner</td> <td width="160" bgcolor = "#ffffbb">Telephone</td> <td width="103" bgcolor = "#ffffbb"> </td> <td width="68" bgcolor = "#ffffbb">Food </td> <td width="93" bgcolor = "#ffffcc">Breed</td> </tr> <?php // print each form field’s value print( "<td>$petname</td> <td>$ownername</td> <td>$ownertelno</td> <td>$owner </td> <td>$petfood</td> <td>$petbreed</td>" ); ?> </table> <br /><br /><br /> We’re printing a table of what has come from the form via the post Intro to Scripting Using PHP PHP and Forms PHP and Databases

26 PHP – MySQL – Pet Form Example – PHP Code (cont’d)
// Create MySQL connection $database = new mysqli("localhost", "testuser1", "*********", "testuser1_pets"); // Check connection if ($database->connect_error) { die("Connection failed: " . $database->connect_error); } if ( !( $result = $database->query ( "SELECT ID FROM Petfoods WHERE Name = '$petfood'") ) ) print ("Warning! could not execute food query <br />" ); $row = $result->fetch_assoc(); $foodid = $row["ID"]; if (! ( $result = $database->query ( "SELECT OwnerID FROM PetOwners WHERE Name = '$ownername'") ) ) print ("Warning! could not execute owner query <br />" ); if ( $row["OwnerID"] == 0 ) // if the owner isn’t already there { $database->query ("INSERT INTO PetOwners " . " ( Name , TelNo , ) " . "VALUES ( '$ownername' , '$ownertelno' , '$owner ' )"); $ownerid = $database->insert_id; This gets the key ID of the chosen pet food. Intro to Scripting Using PHP PHP and Forms PHP and Databases

27 PHP – MySQL – Pet Form Example – PHP Code (cont’d)
It’s often a good idea to build the query first and then execute it as a variable Update the owner info else { $ownerid = $row["OwnerID"]; $database->query ("UPDATE PetOwners SET Name = '$ownername', TelNo = '$ownertelno', = '$owner ' WHERE ID = '$ownerid'"); } // Now that the owner id and food id have both been found, we can add the pet to the pet database $query = "INSERT INTO Pets " . "( Name , Breed , Eats, OwnerID) " . "VALUES ( '$petname' , '$petbreed', '$foodid', '$ownerid' )" ; if ( !( $result = $database->query ( $query ) ) ) { die ( "Could not execute query! " . $database->connect_error ); $database->close(); ?> </body> </html> Intro to Scripting Using PHP PHP and Forms PHP and Databases

28 More Practice Write a PHP script that displays a drop-down select list of clerk names from your database last week (If you still don’t have any clerks in your database you can try something different, or quickly add some clerks) Upload the script to your server and run it (you don’t need to create an HTML form) You don’t have to worry about displaying anything yet from the user’s select choice

29 If you’re falling behind
Review HTML forms and tables Study basic PHP syntax, including variables (like $var), loops, print and echo statements, etc. (look at readings and w3schools tutorials) Make sure you understand interaction between forms and PHP variables (using “post”) Make sure you understand what has to be on the server Touch base with me if you might need help Intro to Scripting Using PHP PHP and Forms PHP and Databases

30 Tips on debugging PHP Don’t expect your scripts to work right away!
Imitate the examples, but don’t cut and paste from Powerpoint – it may put in incorrect characters, or invisible (and illegal) characters Make heavy use of extra “print” and “echo” statements To isolate problems, you can test different parts of your code by commenting out other parts using /* and */ -- then gradually remove the comments as you’re sure the other parts run Use a debugger like to test your syntax, but the database methods won’t be defined and the database won’t be accessible PHP pages usually won’t load at all if there are any syntax errors in the code – so you can’t debug until you isolate Use Notepad++ to match parens, braces, etc. Some common mistakes: forgetting $ for variables, missing or unmatched quotes, missing “;” at end of line, making changes and forgetting to upload, … Intro to Scripting Using PHP PHP and Forms PHP and Databases

31 Recap Covered basics of PHP programming (variables, expressions, data and control structures) Showed interaction between HTML forms and PHP via HTTP “Post” Demonstrated PHP MySQL connection Started to put it all together Intro to Scripting Using PHP PHP and Forms PHP and Databases


Download ppt "Paul Jacobs The iSchool University of Maryland Thursday, Oct. 12, 2017"

Similar presentations


Ads by Google