PHP

From Got Opinion Wiki
Jump to navigation Jump to search

PHP is a server side scripting language.

Basic Syntax & Commands

PHP statements are always terminated with semicolon (;).

Single quotes are used to mark start and end of text ('')

All variable names in PHP start with dollar sign ($).

PHP is a loosely typed language. Variables may contain any type of data.

Example:

$variable_name = "Semper Fidelis";

Equal sign is called the assignment operator since it assigns values to variables.

Comments begin with // or /* */

arithmetic operators enable you to add, subtract, multiply, & divide.

concatenation operator allows you to add strings of text.

Example:

$variable_name = "Hello" . " there" . " world!";

Assigns value of "Hello there world!" without quotes.

Examples:

variable comment
$var1 = 'PHP'; Assigns value of "PHP" to var1
$var2 = 5; Assigns value of 5 to $var2
$var3 = $var2 + 1; Assigns value of 6 to $var3
$var2 = $var1; Assigns value of "PHP" to $var2
echo($var1); Outputs "PHP"
echo($var2); Outputs "PHP"
echo($var3); Outputs 6
echo($var1 . ' rules!'); Outputs "PHP rules!"
echo("var1 rules!"); Outputs "PHP rules!"
echo('var1 rules!'); Outputs '$var1 rules!'

NOTE: Double quotes around text enables the variable name to be inserted & value is displayed. This is called variable interpolation. Single quotes will not interpolate the variable name.

Arrays

A special variable that contains multiple values.

Simple format:

$array_name = array('test1', 'test2', 69);

To retrieve a value stored in an array you need the index.

Generally, arrays use incrementing integers that start with zero as their indices. Indices act as pointers to precisely locate a value in an array.

Expanding on simple format:

code comment
echo($array_name[0]); Outputs 'test1'
echo($array_name[1]); Outputs 'test2'
echo($array_name[2]); Outputs 69
$array_name[1] = 'wiki1'; Assign a new value
$array_name[3] = 'wiki2'; Create a new element
$array_name[] = 'transformers'; Add element to end of array.
echo($array_name[4]); Outputs "transformers"

Arrays can use strings for indices. This is called an associative array because we can associate values with meaningful indices.

Example:

$weight['robert'] = 225;

$weight['gene'] = 180;

$weight['julie'] = 103;

Array Variables

Array variables useful to HTML

Array variable comment
$_GET
$_POST
$_REQUEST
$_SERVER

Functions

Functions are good for your health.

function syntax description
echo outputs data to browser
urlencode takes any special characters in a string (like spaces) & converts them into special codes to appear in php query strings
mysql_connect Enables connection to MySQL database, returns a number that identifies the connection that has been established
mysql_select_db Selects database table that PHP will use.
mysql_query Enables PHP to send MySQL queries to MySQL db
exit( ); Commands PHP to stop reading page.
mysql_affected_rows ( ); Returns number of rows affected for DELETE, INSERT, and UPDATE queries. MySQL tracks the number of rows that were affected.
isset returns a value of true if the identified variable has a value
CURDATE() returns current date
blah blah
blah blah


mysql_connect example

Example code:

$dbcnx = @mysql_connect ('db_hostname', 'db_user_name', 'db_user_password');

if (!$dbcnx) {

echo ( '<p>Unable to connect to the ' .

'database server at this time.</p>' );

exit ();

}
  • The '@' symbol tells the function to fail silently which enables the coder to display your own message.
  • The '!' symbol flips the $dbcnx value. A returned number for $dbcnx is true (your code successfully connected to MySQL db. !$dbcnx means a successful db connection results in false and the if statement would not execute. !$dbcnx means a failed db connection results in true and the if statement would execute (print the custom error message).
  • exit() function causes php to stop reading the page

mysql_select_db example

After your code successfully connets to the MySQL db you must tell PHP which db table to use.

Example basic code:


mysql_select_db ('db_name', $dbcnx );


  • The function contains the db identifier $dbcnx. This parameter is optional but I will use it for completeness. The function will default to the last connection opened.
  • Function returns true when it's successful and false if an error occurs.

Example basic code with error handling:


if (! @mysql_select_db('db_name', $dbcnx) ) {
die ( '<p>Unable to locate the db_name ' .
'database at this time.</p>' );
}

  • die function works like echo except the script exits after
  • Executing die is equivalent to echo followed by exit

mysql_query example

Example code:


mysql_query ( query, connection_id ) ;

  • query is a string that contains the SQL command we want to execute
  • connection_id is optional parameter
  • Returns true (success) or false (failure) for most SQL queries. SELECT queries view data in db so it requires more than true or false.
  • With SELECT query mysql_query returns a number that identifies a result set which contains a list of all the rows (entries) returned from the query.
  • False is always returned if query fails.

More example code:


$result = @mysql_query ('SELECT column_name0, column_name1, ... FROM table_name');

if ( !$result )  {

die ('<p>Error performing query: ' . mysql_error() .

'</p>');
}

User Interaction & Forms

Formats, tips, and suggestions for user interaction & forms.

Variables can be separated in s query string by an ampersand (&). You may use the ampersand multiple times.

Web pages that can decide whether to display more than one pages is a multipurpose page.

Sample multipurpose page in the HTML body tags:


<?php if ( condition ) { ?>

HTML content to display if condition is true

<?php } else { ?>

HTML content to display if condition is false

<?php } ?>

Control Structures

if-else statement

if ( condition ) {

executed if condition is true

} else {

executed if condition false

while loop

while ( conditions ) {

statements execute if true, then repeat, until false

}

for loop


for ( initialize; condition; update ) {

statement(s) to execute repeatedly while condition is true

}

Operators

operator meaning
and or && compares two conditions both must be true
or or || compares two and either must be true
! negation operator or not operator, reverses a returned value from true to false or vice versa
== equal-to operator
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal