PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. What is PHP?

• • • •

PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use

What is a PHP File?

• • •

PHP files can contain text, HTML, CSS, JavaScript, and PHP code PHP code are executed on the server, and the result is returned to the browser as plain HTML PHP files have extension ".php"

What Can PHP Do?

• • • • •

PHP can generate dynamic page content PHP can create, open, read, write, delete, and close files on the server PHP can collect form data PHP can add, delete, modify data in your database PHP can be used to control user-access

With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML. Why PHP?

• • • • •

PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP supports a wide range of databases PHP is free. Download it from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

What Do I Need? To start using PHP, you can:

• •

Find a web host with PHP and MySQL support Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support If your server has activated support for PHP you do not need to do anything. Just create some .php files, place them in your web directory, and the server will automatically parse them for you. You do not need to compile anything or install any extra tools. Because PHP is free, most web hosts offer PHP support.

Page 2 of 51

Set Up PHP on Your Own PC However, if your server does not support PHP, you must:

• • •

install a web server install PHP install a database, such as MySQL

PHP 5 Syntax A PHP script is executed on the server, and the plain HTML result is sent back to the browser. A PHP script can be placed anywhere in the document. A PHP script starts with Example

My first PHP page



Page 3 of 51

Comments in PHP A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is looking at the code. Comments can be used to:

• Let others understand what you are doing • Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. • Comments can remind you of what you were thinking when you wrote the code PHP supports several ways of commenting:

PHP Case Sensitivity In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. In the example below, all three echo statements below are legal (and equal): "; echo "Hello World!
"; EcHo "Hello World!
"; ?>

Page 4 of 51

However; all variable names are case-sensitive. In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables): "; echo "My house is " . $COLOR . "
"; echo "My boat is " . $coLOR . "
"; ?>

PHP 5 Variables Creating (Declaring) PHP Variables In PHP, a variable starts with the $ sign, followed by the name of the variable: Example Rules for PHP variables:

• • • •

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 (A-z, 0-9, and _) Variable names are case-sensitive ($age and $AGE are two different variables) • Output Variables The PHP echo statement is often used to output data to the screen. The following example will show how to output text and a variable: The following example will produce the same output as the example above:
Page 5 of 51

?> The following example will output the sum of two variables:

PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes:

• • •

local global static

Global and Local Scope A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: Variable x inside function is: $x

"; } myTest(); echo "

Variable x outside function is: $x

"; ?> A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: Example Variable x inside function is: $x

"; } myTest(); // using x outside the function will generate an error echo "

Variable x outside function is: $x

"; ?> ->You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

Page 6 of 51

PHP The global Keyword The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function): Example PHP The static Keyword Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword when you first declare the variable: Then, each time the function is called, that variable will still have the information it contained from the last time the function was called. Note: The variable is still local to the function.

PHP Constants A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script. Syntax define(name, value, case-insensitive)

Page 7 of 51

Parameters:

• • •

name: Specifies the name of the constant value: Specifies the value of the constant case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

The example below creates a constant with a case-sensitive name: The example below creates a constant with a case-insensitive name: Constants are Global Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, even if it is defined outside the function:

PHP - The if Statement The if statement is used to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true; } Example

Page 8 of 51

PHP - The if...else Statement if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } Example

The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } Example

Page 9 of 51

PHP 5 while Loops The while loop executes a block of code as long as the specified condition is true. Syntax while (condition is true) { code to be executed; } Example "; $x++; } ?>

The PHP for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (init counter; test counter; increment counter) { code to be executed; } Parameters:

• •

init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value • The example below displays the numbers from 0 to 10: Example "; } ?>

PHP 5 Functions Create a User Defined Function in PHP A user defined function declaration starts with the word "function": Syntax function functionName() { code to be executed; }

Page 10 of 51

Note: A function name can start with a letter or underscore (not a number). Example

PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. Example "; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?> The following example has a function with two arguments ($fname and $year): Example "; } familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?>

PHP Functions - Returning values To let a function return a value, use the return statement: Example "; echo "7 + 13 = " . sum(7, 13) . "
"; echo "2 + 4 = " . sum(2, 4); ?>

Page 11 of 51

PHP 5 Arrays An array stores multiple values in one single variable: Example Create an Array in PHP In PHP, the array() function is used to create an array: array(); In PHP, there are two types of arrays:

• •

Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys

PHP Indexed Arrays There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota"; Get The Length of an Array - The count() Function The count() function is used to return the length (the number of elements) of an array: Example

PHP Associative Arrays Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: $age = array("Peter"=>"35", "Ben"=>"37", “Joe"=>"43"); or: $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43"; Example "35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> 


Page 12 of 51

MYSQL SQL is a standard language for accessing databases. What Can SQL do? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database Using SQL in Your Web Site To build a web site that shows data from a database, you will need: An RDBMS database program (i.e. MS Access, SQL Server, MySQL) To use a server-side scripting language, like PHP or ASP To use SQL to get the data you want RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. The Most Important SQL Commands SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database SQL SELECT Statement The SELECT statement is used to select data from a database. SQL SELECT Syntax SELECT column_name,column_name FROM table_name; and SELECT * FROM table_name; Example SELECT StudentName,City FROM tblStudent; Example SELECT * FROM tblStudent;

Page 13 of 51

The SQL SELECT DISTINCT Statement In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values. SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name,column_name FROM table_name; Example SELECT DISTINCT City FROM tblStudent;

The SQL WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT column_name,column_name FROM table_name WHERE column_name operator value; SELECT * FROM tblStudent WHERE Country=‘kuwait';

Text Fields vs. Numeric Fields SQL requires single quotes around text values. However, numeric fields should not be enclosed in quotes: Example SELECT * FROM Customers WHERE StudentId=1; The SQL AND & OR Operators The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. Example SELECT * FROM tblStuent WHERE Country='Kuwait' AND GPA='3'; Example SELECT * FROM Customers WHERE Country='Kuwait' OR GPA='3';

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC, column_name ASC|DESC;

Page 14 of 51

Example SELECT * FROM tblStudent ORDER BY Country; Example SELECT * FROM Customers ORDER BY Country DESC;

The SQL INSERT INTO Statement The INSERT INTO statement is used to insert new records in a table. INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,…); Example INSERT INTO tblStudent (name, city, country, gpa) VALUES (‘ahmad’,’farwaniyah','kuwait','4');

The SQL UPDATE Statement The UPDATE statement is used to update existing records in a table. SQL UPDATE Syntax UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value; Example UPDATE tblSutent SET gpa=‘4' WHERE id = 4; The SQL DELETE Statement The DELETE statement is used to delete rows in a table. SQL DELETE Syntax DELETE FROM table_name WHERE some_column=some_value; Example DELETE FROM tblStudent WHERE id=2; Delete All Data It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name;

Page 15 of 51

SQL Joins An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN returns all rows from multiple tables where the join condition is met. Example SELECT tblResult.subject,tblResult.scroe, tblStudent.name FROM tblResult INNER JOIN tblStudent ON tblResult.stId=tblStudent.id;

PHP MySQL Database With PHP, you can connect to and manipulate databases. MySQL is the most popular database system used with PHP.

Open a Connection to MySQL Before we can access data in the MySQL database, we need to be able to connect to the server: connect_error) { die("Database connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>

PHP Select Data From MySQL Select Data From a MySQL Database The SELECT statement is used to select data from one or more tables: SELECT column_name(s) FROM table_name or we can use the * character to select ALL columns from a table: SELECT * FROM table_name

Page 16 of 51

Select Data With MySQLi The following example selects the id, name and city columns from the tblStudent table and displays it on the page: connect_error) { die("Database connection failed: " . mysqli_connect_error()); } $sql = "SELECT id, name, city FROM tblStudent"; $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["name"]. " - city: " . $row["city"]. "
"; } } else { echo "0 results"; } ?>

Page 17 of 51

PHP Insert Data Into MySQL The INSERT INTO statement is used to add new records to a MySQL table: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) connect_error) { die("Database connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO tblStudent (name, city, country,gpa) VALUES ('Ahmad', 'Ardiyah', 'Franch',2.5)"; $result = $conn->query($sql); if ($result) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; } ?>

Page 18 of 51

PHP Update Data in MySQL The UPDATE statement is used to update existing records in a table: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

*Tip: PHP 5 Include Files The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website. Example 1 Assume we have a standard footer file called "footer.php", that looks like this: Copyright © 1999-" . date("Y") . " smart-kw.com

”; ?> Example

Welcome to my home page!

Some text.

Some more text.



Update Code Example query($sql); if ($result) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } ?>

Page 19 of 51

PHP Delete Data From MySQL The DELETE statement is used to delete records from a table: DELETE FROM table_name WHERE some_column = some_value query($sql); if ($result) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } ?> PHP Form (Get & Post) Get: Data transfer to server and will show in the URL.

Post: Data transfer to server and will not show in the URL

Page 20 of 51

Example query($sql); if ($result) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; } } ?>

name

city

country

GPA



Page 21 of 51

JSON JSON stands for JavaScript Object Notation JSON is a lightweight data-interchange format JSON Objects JSON objects are written inside curly braces. Example query($sql); if ($result) { $response = array('result' => 1, 'message' => "Success"); echo json_encode($response); } else { $response = array('result' => 0, 'message' => "Fail"); echo json_encode($response); } ?> JSON Arrays: JSON arrays are written inside square brackets. query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $std[] = $row; } } echo json_encode($std); ?> Result: [{"id":"1","gpa":"2.4"},{"id":"2","gpa":"2"},{"id":"4","gpa":"2.2"},{"id":"5","gpa":"2.5"},{"id":"6","gpa":"2"}, {"id":"7","gpa":"2.5"},{"id":"8","gpa":"4"},{"id":"9","gpa":"0"}]

Page 22 of 51

PHP Mysql.pdf

Page 1 of 21. PHP. PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web. pages. PHP is a widely-used, free, and ...

198KB Sizes 4 Downloads 202 Views

Recommend Documents

Pfff: Parsing PHP - GitHub
Feb 23, 2010 - II pfff Internals. 73 ... 146. Conclusion. 159. A Remaining Testing Sample Code. 160. 2 ..... OCaml (see http://caml.inria.fr/download.en.html).

PHP engineer.pdf
iO mission. Page 3 of 26. PHP engineer.pdf. PHP engineer.pdf. Open. Extract. Open with. Sign In. Main menu. Displaying PHP engineer.pdf. Page 1 of 26.

EOS : Unstoppable Stateful PHP
managed in the database or in transactional queues [4, 7, etc.], but this entails a ... spinlock-based shared/exclusive latches. 1.1 Review of Interaction Contracts. The framework considers a set of interacting components of three different types. (i

PHP Credits -
'--sysconfdir=/private/etc' '--with-apxs2=/usr/sbin/apxs' '--enable-cli' '--with-config- file-path=/etc' '--with-libxml-dir=/usr' '--with-openssl=/usr' '--with-kerberos=/usr' '--with-zlib=/usr' .... CharConv. No. Protocols tftp, ftp, telnet, dict, ld

Pfff, a PHP frontend
Page 1. Pfff, a PHP frontend. Yoann Padioleau [email protected]. February 14, 2010. Page 2. Copyright cс 2009-2010 Facebook. Permission is ...

5. PHP bangla tutorial php basic.pdf
... below to open or edit this item. 5. PHP bangla tutorial php basic.pdf. 5. PHP bangla tutorial php basic.pdf. Open. Extract. Open with. Sign In. Main menu.

pdf-1445\php-anthology-object-oriented-php-solutions-vol2 ...
Try one of the apps below to open or edit this item. pdf-1445\php-anthology-object-oriented-php-solutions-vol2-applications-by-harry-fuecks.pdf.

EOS : Unstoppable Stateful PHP
INTRODUCTION. A growing number of businesses deliver mission-critical applica- tions (stock trading, auctions, etc.) to their customers as Web. Services.

PHP+OOP.pdf
Whoops! There was a problem loading more pages. Whoops! There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. PHP+OOP.pdf. PHP+OOP.pdf. Open. Extract. Open with.

pdf xml php
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. pdf xml php.

Taking PHP Seriously [pdf] - GitHub
... reinvented PHP better, but that's still no justification”. • http://colinm.org/language_checklist.html. • Etc. ... The Case Against PHP (2). • Schizophrenia about ...

view pdf php
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. view pdf php.

php to pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. php to pdf.

Taking PHP Seriously [pdf] - GitHub
The Case Against PHP (2). • Schizophrenia about value/reference semantics. /*. * Probably copy $a into foo's 0'th param. * Unless $a is a user-‐defined object; and unless. * foo's definition specifies that arg 0 is by. * reference. */ foo($a); ..

pdf php tutorials
Page 1. Whoops! There was a problem loading more pages. pdf php tutorials. pdf php tutorials. Open. Extract. Open with. Sign In. Main menu. Displaying pdf php ...

Better PHP Development.pdf
JavaScript, PHP, design, and more. ii Better PHP Development. Page 3 of 151. Better PHP Development.pdf. Better PHP Development.pdf. Open. Extract.

Better PHP Development.pdf
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. Better PHP Development.pdf. Better PHP Development.pdf. Open.

AJAX and PHP - Navodaya Foundation
modern web browser, such as Internet Explorer, Mozilla Firefox, Opera, or Safari. • Web applications make ... Although the history of the Internet is a bit longer, 1991 is the year when HyperText Transfer. Protocol (HTTP) ... the location bar of Fi

PHP-MySQL Book.pdf
PHP-MySQL Book.pdf. PHP-MySQL Book.pdf. Open. Extract. Open with. Sign In. Main menu. Displaying PHP-MySQL Book.pdf.