PHPلغة PHP

الشريحة 1 من 25

مقدمة الفصل

ماذا ستتعلم في هذا الفصل

  1. Manipulate data of various types.
  2. Use operators, arrays and control statements.
  3. Use regular expressions to search for text that matches a pattern.
  4. Construct programs that process form data.
  5. Store data on the client using cookies.
  6. Create programs that interact with MySQL databases.
تفاصيل المصدرالفصل 6 · الشريحة ⁦3⁩
المصدر
الفصل 6 · الشريحة ⁦3⁩

What is PHP?ما PHP؟

What PHP is and a simple PHP program

PHP (PHP: Hypertext Preprocessor)
The most popular server-side scripting language for creating dynamic web pages. PHP is open source and platform independent, and supports a large number of databases.
  • PHP code is embedded in text-based documents such as HTML, but is interpreted by a server before being delivered to the client.
  • PHP script file names end with .php.
  • Code is inserted between the scripting delimiters <?php and ?>.
تفاصيل المصدرالفصل 6 · الشرائح ⁦4–5⁩
المصدر
الفصل 6 · الشرائح ⁦4–5⁩

Variables, statements and commentsالمتغيرات والجمل والتعليقات

What PHP is and a simple PHP program

  • Variables are preceded by a $ and are created the first time they're encountered. Names are case sensitive.
  • Statements terminate with a semicolon (;) — forgetting it is a syntax error.
  • Comments: // or # for one line; /* … */ for several lines.
  • A variable inside a double-quoted string is interpolated (its value is inserted) — on the server, before the page is sent.
  • PHP variables are loosely typed: they can hold different types of data at different times.

من الشرائح

  • $name = "Paul"; … print( "Welcome to PHP, $name!" ); → Welcome to PHP, Paul!
تفاصيل المصدرالفصل 6 · الشرائح ⁦6–8⁩
المصدر
الفصل 6 · الشرائح ⁦6–8⁩

سؤال سريع

What PHP is and a simple PHP program

Which statement about PHP is correct?

تفاصيل المصدرالفصل 6 · الشرائح ⁦4–5⁩
المصدر
الفصل 6 · الشرائح ⁦4–5⁩

PHP data typesأنواع البيانات

Data types and converting between them

Fig. 19.2 — PHP types
TypeالنوعDescription (Fig. 19.2)الوصف
int, integerWhole numbers (numbers without a decimal point)
float, double, realReal numbers (numbers containing a decimal point)
stringText enclosed in single ('') or double ("") quotes
bool, booleantrue or false
arrayGroup of elements
objectGroup of associated data and methods
resourceAn external source — usually information from a database
NULLNo value
تفاصيل المصدرالفصل 6 · الشريحة ⁦9⁩
المصدر
الفصل 6 · الشريحة ⁦9⁩

Converting between typesالتحويل بين الأنواع

Data types and converting between them

gettype
Returns the current type of its argument.
settype
Takes a variable and its new type. Can result in loss of data: doubles are truncated when converted to integers.
String → number
Uses the number at the beginning of the string; if there is none, the string evaluates to 0.
Casting
e.g. (integer) $data — does not change the variable's content; it creates a temporary copy of its value.
Concatenation (.)
Combines multiple strings.

من الشرائح

  • "3.5 seconds" → settype double: 3.5 → settype integer: 3 → back to string: "3"
  • "98.6 degrees" → (double) 98.6, (integer) 98; afterwards still a string
تفاصيل المصدرالفصل 6 · الشرائح ⁦10, 11, 13, 14⁩
المصدر
الفصل 6 · الشرائح ⁦10, 11, 13, 14⁩

سؤال سريع

Data types and converting between them

$v = "7.9 kg"; settype( $v, "double" ); print( $v ); settype( $v, "integer" ); print( " $v" ); What is printed?

تفاصيل المصدرالفصل 6 · الشريحة ⁦10⁩
المصدر
الفصل 6 · الشريحة ⁦10⁩

Constants and uninitialized variablesالثوابت والمتغيرات غير المهيأة

Constants, uninitialized variables, operators and keywords

define
Creates a named constant: the name and the value; an optional third boolean makes it case insensitive (constants are case sensitive by default). Assigning a value to a constant after it is declared is a syntax error.
  • An uninitialized variable in a numeric context evaluates to 0 — e.g., multiplying by it gives 0. Initialize variables before using them.
  • Keywords may not be used as function, method, class or namespace names.

من الشرائح

  • define( "VALUE", 5 ); $a = $a + VALUE;
تفاصيل المصدرالفصل 6 · الشرائح ⁦15, 16, 19⁩
المصدر
الفصل 6 · الشرائح ⁦15, 16, 19⁩
ملاحظات حول المصدر (1)
  • تقول الشريحة 15 إن القيمة غير المعرّفة في سياق نصي تساوي "undef"، ويقول تعليق الكود في الشريحة 18 إنها "".

Operator precedenceأسبقية العمليات

Constants, uninitialized variables, operators and keywords

From Fig. 19.6 (highest first, selected rows):

  • ++ -- (increment, decrement)
  • ! (not)
  • \* / % (multiplication, division, modulus) — left to right
  • + - . (addition, subtraction, concatenation) — left to right
  • < > <= >= (relational)
  • == != === !== (equality, identity)
  • && then || (logical AND, OR) — left to right
  • ?: (ternary conditional)
  • = += -= \*= /= %= .= (assignment) — right to left
  • and, xor, or — left to right
تفاصيل المصدرالفصل 6 · الشرائح ⁦21–25⁩
المصدر
الفصل 6 · الشرائح ⁦21–25⁩

Arrays and associative arraysالمصفوفات

  • Array names begin with $; elements are accessed with an index in [ ].
  • Assigning to an element of a nonexistent array creates it; omitting the index ($a[] = …) appends to the end.
  • count returns the number of elements; array creates an array starting at index 0.
Associative array
An array with nonnumeric indices, created with => (index on the left, value on the right).
reset
Sets the internal pointer to the first element.
key
Returns the index of the element currently referenced.
next
Moves the internal pointer to the next element.
تفاصيل المصدرالفصل 6 · الشرائح ⁦26–27⁩
المصدر
الفصل 6 · الشرائح ⁦26–27⁩

سؤال سريع

Arrays

$list = array( "red", "green" ); $list[] = "blue"; print( count( $list ) . " " . $list[ 2 ] ); What is printed?

تفاصيل المصدرالفصل 6 · الشريحة ⁦26⁩
المصدر
الفصل 6 · الشريحة ⁦26⁩

foreachالحلقة foreach

Arrays

foreach
Designed for iterating through arrays: the array, the keyword as, then two variables — the first gets the index, the second the value. With only one variable after as, it gets the value.

من الشرائح

  • foreach ( $fourth as $element => $value ) print( "<p>$element is the $value month</p>" ); → January is the first month …
تفاصيل المصدرالفصل 6 · الشرائح ⁦28, 31⁩
المصدر
الفصل 6 · الشرائح ⁦28, 31⁩

سؤال سريع

Arrays

$cap = array( "KSA" => "Riyadh", "UAE" => "Abu Dhabi" ); foreach ( $cap as $c => $city ) print( "$city-$c " ); What is printed?

تفاصيل المصدرالفصل 6 · الشريحة ⁦28⁩
المصدر
الفصل 6 · الشريحة ⁦28⁩

String comparisonsمقارنة النصوص

  • String tasks can use the equality and relational operators (==, !=, <, <=, >, >=).
strcmp
Compares two strings and returns -1 if the first alphabetically precedes the second, 0 if they are equal, 1 if the first follows the second.
تفاصيل المصدرالفصل 6 · الشرائح ⁦32–34⁩
المصدر
الفصل 6 · الشرائح ⁦32–34⁩

سؤال سريع

String comparisons

What does strcmp( "mango", "apple" ) return?

تفاصيل المصدرالفصل 6 · الشريحة ⁦32⁩
المصدر
الفصل 6 · الشريحة ⁦32⁩

Regular expressionsالتعابير النمطية

Regular expression
A series of characters that serve as pattern-matching templates (search criteria) in strings, text files and databases.
preg_match( pattern, string [, matches] )
Searches a string for a pattern (PCRE). The optional third argument stores the matches: element 0 = whole match, then each parenthetical part.
^ $ .
Beginning of a string; end of a string; any single character.
[ … ] and ranges
Match any single character from the list; ranges use a dash, e.g. [a-zA-Z].
\b
Beginning / end of a word — matches whole words.
Quantifiers
How often a character or set of characters can appear in a match.
[[:alpha:]]
Character classes are enclosed by [: and :]; inside another set of brackets they match all characters in the class.
preg_replace( pattern, replacement, string )
Returns the modified string; used to remove matches before searching again.
تفاصيل المصدرالفصل 6 · الشرائح ⁦35, 38, 39, 40, 41, 42⁩
المصدر
الفصل 6 · الشرائح ⁦35, 38, 39, 40, 41, 42⁩
ملاحظات حول المصدر (1)
  • تقول الشريحة 35 إن preg_match تعيد طول النص المطابق وتطابق دون حساسية لحالة الأحرف؛ نُقلت كما هي ولم يُبنَ عليها سؤال.

سؤال سريع

Regular expressions

Which pattern matches "Done" only when it is at the very end of $text?

تفاصيل المصدرالفصل 6 · الشريحة ⁦38⁩
المصدر
الفصل 6 · الشريحة ⁦38⁩

Form processingمعالجة النماذج

Superglobal arrays
Associative arrays predefined by PHP holding variables from user input, the environment or the web server, accessible in any variable scope. $_GET and $_POST hold data sent by HTTP get and post requests.
\ (backslash)
Escapes the normal meaning of a character in a string.
die
Terminates script execution; its optional string argument is printed as the script exits.

من الشرائح

  • if ( !preg_match( "/^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/", $_POST["phone"] ) ) { print( "…Invalid phone number…" ); die(); }
تفاصيل المصدرالفصل 6 · الشرائح ⁦43, 44, 45, 49, 51⁩
المصدر
الفصل 6 · الشرائح ⁦43, 44, 45, 49, 51⁩

سؤال سريع

Form processing and business logic

A form with method = "post" has an input named email. How does the PHP script read the value?

تفاصيل المصدرالفصل 6 · الشريحة ⁦43⁩
المصدر
الفصل 6 · الشريحة ⁦43⁩

Reading from a MySQL databaseقواعد البيانات

Reading from a database

FunctionالدالةWhat it does (slides 52–53)وظيفتها
mysql_connect(host, user, password)
  • Connects
  • returns a database handle, or false on failure
mysql_select_db
  • Selects and opens the database
  • true or false
mysql_query(query, database)
  • Runs the query
  • returns a result resource, or false
  • also INSERT/DELETE
mysql_errorReturns any error strings from the database
mysql_closeCloses the connection given as its argument
mysql_fetch_rowReturns an array of the column values in the current row
  • Fig. 19.16 prints the number of results with mysql_num_rows( $result ).
تفاصيل المصدرالفصل 6 · الشرائح ⁦52, 53, 57⁩
المصدر
الفصل 6 · الشرائح ⁦52, 53, 57⁩

سؤال سريع

Reading from a database

In what order does Fig. 19.16 use these functions to read data?

تفاصيل المصدرالفصل 6 · الشرائح ⁦52–53⁩
المصدر
الفصل 6 · الشرائح ⁦52–53⁩

Cookiesملفات تعريف الارتباط

Cookie
A piece of information stored by a server in a text file on a client's computer to maintain information about the client during and between browsing sessions. A server can access only the cookies it has placed.
setcookie( name, value [, expiration] )
No expiration → session cookie (until the browser closes); with expiration → persistent cookie. Only the name → the cookie is deleted. Must be called before any other output (sent with the HTTP header).
$_COOKIE
Superglobal array with all cookie values indexed by their names.
تفاصيل المصدرالفصل 6 · الشرائح ⁦58, 59, 61⁩
المصدر
الفصل 6 · الشرائح ⁦58, 59, 61⁩

سؤال سريع

Cookies

setcookie( "theme", "dark" ); is called with no third argument. What kind of cookie is this?

تفاصيل المصدرالفصل 6 · الشريحة ⁦58⁩
المصدر
الفصل 6 · الشريحة ⁦58⁩

Dynamic contentالمحتوى الديناميكي

isset
Determines whether the $_POST array contains keys for the form fields.
$$variable
A variable variable: the value of the variable whose name equals the value of $variable.
mysql_real_escape_string
Inserts a backslash (\) before any special characters in the passed string.

من الشرائح

  • $fname = isset( $_POST[ "fname" ] ) ? $_POST[ "fname" ] : "";
تفاصيل المصدرالفصل 6 · الشرائح ⁦64, 66⁩
المصدر
الفصل 6 · الشرائح ⁦64, 66⁩

الخلاصة

تفاصيل المصدر
المصدر
الفصل 6

خريطة الفصل

    1. 1مقدمة الفصل
  1. What PHP is and a simple PHP programما PHP وأول برنامج

    1. 2What is PHP?ما PHP؟
    2. 3Variables, statements and commentsالمتغيرات والجمل والتعليقات
    3. 4سؤال سريع: PHP
  2. Data types and converting between themأنواع البيانات والتحويل بينها

    1. 5PHP data typesأنواع البيانات
    2. 6Converting between typesالتحويل بين الأنواع
    3. 7سؤال سريع: settype
  3. Constants, uninitialized variables, operators and keywordsالثوابت والمتغيرات غير المهيأة والعمليات

    1. 8Constants and uninitialized variablesالثوابت والمتغيرات غير المهيأة
    2. 9Operator precedenceأسبقية العمليات
  4. Arraysالمصفوفات

    1. 10Arrays and associative arraysالمصفوفات
    2. 11سؤال سريع: المصفوفات
    3. 12foreachالحلقة foreach
    4. 13سؤال سريع: foreach
  5. String comparisonsمقارنة النصوص

    1. 14String comparisonsمقارنة النصوص
    2. 15سؤال سريع: strcmp
  6. Regular expressionsالتعابير النمطية

    1. 16Regular expressionsالتعابير النمطية
    2. 17سؤال سريع: التعابير
  7. Form processing and business logicمعالجة النماذج ومنطق العمل

    1. 18Form processingمعالجة النماذج
    2. 19سؤال سريع: $_POST
  8. Reading from a databaseالقراءة من قاعدة البيانات

    1. 20Reading from a MySQL databaseقواعد البيانات
    2. 21سؤال سريع: قاعدة البيانات
  9. Cookiesملفات تعريف الارتباط

    1. 22Cookiesملفات تعريف الارتباط
    2. 23سؤال سريع: الكوكيز
    1. 24Dynamic contentالمحتوى الديناميكي
    1. 25الخلاصة