Download presentation
Presentation is loading. Please wait.
1
CIS 388 Internet Programming
PHP/MySQL Review
2
What is PHP? PHP is a server-side scripting language designed primarily for web development but also used as a general-purpose programming language. PHP stands for the recursive acronym PHP: Hypertext Preprocessor.[6] PHP code may be embedded into HTML or HTML5 code, or it can be used in combination with various web template systems, web content management systems and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications.[7] The standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on almost every operating system and platform, free of charge.[8] The PHP language evolved without a written formal specification or standard until 2014, leaving the canonical PHP interpreter as a de facto standard. Since 2014 work has gone on to create a formal PHP specification.[9]
3
PHP Basics As a scripting language (like javascript), it does not need to be compiled and it can be placed in the page with HTML code between the PHP scripting tags - <?php code ?> or in a separate/included .php file - <?php include(“path/filename.ext”) ?> The syntax is harder to read and more difficult (similar to javascript) The requestor NEVER sees the code, the code is “parsed” (executed) by the server before sending the file to the requestor (secure!) Lines of code are ended with a semi-colon Functions are “contained” within brackets {} (*single-line if-then-else statements do not have to be in brackets, but should for readability) Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration. Functions are not case sensitive, Variables are case sensitive. (*keep it lowercase when in doubt) Files must be saved with a “.php” extension (*include files called from another file can be other file types html/css/rss/etc…, but only “.php” include files will be executed from an external call)
4
PHP Basics PHP variables should always be declared
A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores
5
PHP Basics PHP Data/variable types (*not required, loosely typed)
String. Integer. Float (floating point numbers - also called double) Boolean. Array. Object. NULL. Resource PHP Operators (+-*/) reference: Comments // This is a one-line comment /* This is a multi line comment yet another line of comment */
6
PHP Basics Programming Syntax/Structure (Similar to Javascript)
Conditionals If-then-else Switch-case Iteration/Loops While/Do…While Loops For/Foreach* Loop (*arrays) Arrays $cars = array("Volvo", "BMW", "Toyota"); Also “0 indexed,” like Javascript reference:
7
Hello World! PHP “Hello World”
<!DOCTYPE HTML> <html> <head> <title>Example</title> </head> <body> <?php echo “Hello World!!"; ?> </body> </html>
8
Advanced PHP PHP includes PHP File Handling
Including an external php or html file in your PHP page – useful for reusing code/functions in many pages (navigational columns, database connections, session/cookie retrieval and validation etc…) Syntax: include 'filename'; <?php include 'footer.php';?> PHP File Handling Open/Read, Create/Modify, and Upload files with PHP fopen(" filename.ext ", “argument") (fread(), fwrite(), and the fclose() are used with fopen) echo readfile(“filename.ext"); (useful for including external data/rss in your page) Uploading files with PHP:
9
Advanced PHP PHP Cookies PHP Session Variables
PHP cookies are just like cookies in javascript and are used to trore bits of information on the client computer Syntax: setcookie(name, value, expire, path, domain, secure, httponly); "Value is: " . $_COOKIE[$cookie_name]; PHP Session Variables PHP session variables are similar to cookies, they store bits of information on the server, and they are open with each browser “session” that connects to the server. A session is started with the session_start() function. Syntax: $_SESSION[“variablename"] = “value"; "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
10
PHP and MySQL PHP allows the web page to get information from and update information stored in a MySQL database Database Connection Code (Object Oriented) <?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
11
PHP and MySQL Create Database (*after MySQL Connection) $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } Create Table (* after Database Created) $sql = "CREATE TABLE MyTable (ColumnName1 TYPE(),…) if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close();
12
PHP and MySQL Insert Data into Database $sql = "INSERT INTO MyTable (ColumnName1) VALUES (‘samplevalue')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } Select/Display Data from a Database $sql = "SELECT id, ColumnName1 FROM MyTable"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " – Column Value: " . $row[“ColumnName1"]. " "<br>"; } } else { echo "0 results"; }
13
PHP and MySQL Delete Records from a Database $sql = "DELETE FROM MyTable WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } Update Records in a Database $sql = "UPDATE MyTable SET ColumnName1=‘NewValue' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } SQL Reference:
14
PHP Login Form <form action="" method="post" name="Login_Form"> <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table"> <?php if(isset($msg)){?> <tr> <td colspan="2" align="center" valign="top"><?php echo $msg;?></td> </tr> <?php } ?> <td colspan="2" align="left" valign="top"><h3>Login</h3></td> <td align="right" valign="top">Username</td> <td><input name="Username" type="text" class="Input"></td> <td align="right">Password</td> <td><input name="Password" type="password" class="Input"></td> <td> </td> <td><input name="Submit" type="submit" value="Login" class="Button3"></td> </table> </form>
15
PHP Login Authentification Code
<?php session_start(); /* Starts the session */ /* Check Login form submitted */ if(isset($_POST['Submit'])){ /* Define username and associated password array */ $logins = array('Alex' => '123456','username1' => 'password1','username2' => 'password2'); /* Check and assign submitted Username and Password to new variable */ $Username = isset($_POST['Username']) ? $_POST['Username'] : ''; $Password = isset($_POST['Password']) ? $_POST['Password'] : ''; /* Check Username and Password existence in defined array */ if (isset($logins[$Username]) && $logins[$Username] == $Password){ /* Success: Set session variables and redirect to Protected page */ $_SESSION['UserData']['Username']=$logins[$Username]; header("location:index.php"); exit; } else { /*Unsuccessful attempt: Set error message */ $msg="<span style='color:red'>Invalid Login Details</span>"; } ?>
16
PHP Session Variable Check
<?php session_start(); /* Starts the session */ if(!isset($_SESSION['UserData']['Username'])){ header("location:login.php"); exit; } ?> Congratulation! You have logged into password protected page. <a href="logout.php">Click here</a> to Logout.
17
PHP Logout Session <?php session_start(); /* Starts the session */ session_destroy(); /* Destroy started session */ header("location:login.php"); /* Redirect to login page */ exit; ?>
18
PHP Reserved Words List of Keywords
These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on--but they're not , really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion. Table K-1. PHP Keywords and or xor __FILE__ exception (PHP 5) __LINE__ array() as break case class const continue declare default die() do echo() else elseif empty() enddeclare endfor endforeach endif endswitch endwhile eval() exit() extends for foreach function global if include() include_once() isset() list() new print() require() require_once() return() static switch unset() use var while __FUNCTION__ __CLASS__ __METHOD__ final (PHP 5) php_user_filter(PHP 5) interface (PHP 5) implements (PHP 5) public (PHP 5) private (PHP 5) protected (PHP 5) abstract (PHP 5) clone (PHP 5) try (PHP 5) catch (PHP 5) throw (PHP 5) cfunction (PHP 4 only) old_function (PHP 4 only) this (PHP 5 only) Source:
19
Additional Resources W3 Schools PHP tutorial: PHP tutorials: PHP scripts and code resources: PHP IDE resources:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.