You are on page 1of 25

Programming in PHP and MySQL

In Just 2 hours!
A crash course in PHP programming and MySQL
integration
By Alireza Nematollahi
Level: Beginner
Copyright © August 2005
This E-Book may be reproduced in any form under GPL laws.
Author's name MUST be on every copy or resource made from this tutorial.
Original copy has been published on ARNIT Education Centre
(http://education.arnit.net)
Programming in PHP
Part 1: Getting to know PHP:
PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script
runs on your web server, not on the user's browser. PHP is relatively new (compared to
languages such as Perl (CGI) and Java) but is quickly becoming one of the most popular scripting
languages on the internet.
PHP syntax is very similar to PERL/CGI and has similarities to JavaScript and C++. These
similarities will be more evident as we move on.
PHP can be embedded into an HTML page or can be used as a standalone scripting program.
Let us take a look at our first PHP program:
<?php
echo "Hello World!";
?>
PHP code should always be encapsulated by <?php and ?> for PHP parser (compiler) to
understand. Some web servers also can understand PHP’s short tags, <? And ?>
The first keyword that we see in this simple program is, “echo”. Echo allows you to display a
string on the display. Similarly, you can use “print” keyword to do the same task.
You must pay extra attention to the semicolon at the end of the code. All PHP codes should be
terminated by a semicolon. This has a few exceptions, such as conditional instruction, which we
will discuss later.
Part 2: PHP variables and constants:
Similar to other programming languages, PHP uses variables to store data and information
temporarily. Also, we can define constants to store data.
One of the differences between PHP and other programming languages, such as C++ and Java
is that, PHP does not use “Data types”. Look at the following Java and PHP programs:
Java Program PHP Program
int number;
number = number++;
$number++;
As is evident from above, PHP does not use data types to distinguish between variables. In other
words, PHP treats all the variables similarly. ( Very similar to JavaScript )
Note that PHP districts variables with the dollar sign ( “$” ) in front of the variable name: i.e.
$number, $name, …
PHP Variables can not start with numbers or contain the following characters:
? . , # $ & | * ( ) { } [ ] (space)
Moreover, note that PHP is a case-sensitive programming language.
You may operate all sorts of operation on variables:
$number = 45;
$number = $number + 2;
PHP Constants:
To define a constant, we use reserved keyword “define”:
Syntax:
define ( string name, mixed value );
i.e.
define ("Test", 23 ); // This defines a constant named “test” with a value of 23
Part 3: PHP variables, Strings and Operators:
Similar to other programming languages, PHP can handle strings. PHP has very advanced string
operations for all sorts of programmers’ needs.
1- String concatenation: To connect two separate strings together to get one string, PHP uses
“.” To accomplish this task:
$first_name = “John ”;
$last_name = “Doe”;
$full_name = $first_name . $last_name; // $full_name will be John Doe
2- Extracting Substrings: Extracting substrings is just the matter of knowing where to start
reading the string and where to stop. For example, we have a string “MynameisJohnDoe”. We
want to extract the last 7 characters out. In PHP we use the substr operator to do that.
Syntax:
Substr ( string String, int start, int end );
Example:
$name_string = “MynameisJohnDoe”;
echo $my_name = substr ( $name_string, 8, 12 ); // $my_name = JohnDoe
If we don’t know the length of the string, we still can extract a string by using negative numbers:
$name_string = “MynameisJohnDoe”;
echo $my_name = substr ( $name_string, -7 ); // $my_name = JohnDoe
The number -7 is the number of characters to be read from the end of the string. Remember that
in PHP numbers start from 0, not 1!
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
M y n a m e i s J o h n D o e
3- Finding the length of a string: Sometimes you need to find the length of a string. This can be
easily done with PHP using “strlen”:
Syntax:
strlen ( string string );
Example:
$name_string = “MynameisJohnDoe”;
echo strlen ($name_string); // prints 15
At first this looks strange! In the table above, we found the number of characters to be 14, but
PHP shows the length of this string is 15! Why? The reason is, PHP starts numbering the
characters from 0, not 1! Counting the 0
th
character, we have 15 characters in this string!
4- Finding position of a string: Sometimes you need to find the position of a string inside
another string. You can easily use, strops to do this:
Syntax:
strpos (string string, character to be found );
Example:
$name_string = "MynameisJohnDoe";
echo strpos($name_string, "D"); // Prints 12!
This example proves that indeed PHP starts numbering characters in a string from 0 not 1!
5- String Replacements: To replace a string inside another string, you may use str_replace.
Syntax:
str_replace (string string_to_be_replaced, string string_to_replace, string string );
Example:
$name_string = "MynameisJohnDoe";
$new_str = str_replace ( "John", "Jane", $name_string );
echo $new_str; // Prints MynameisJaneDoe
6- Pattern Matching:
Not complete
PHP Operators:
1. Math operators: Just like any other programming language, +/-/* and / are the basic math
operators. Table below shows the complete list of PHP math operators:
Example Name Result
-$a Negation Opposite of $a.
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
Part 4: Control Structures:
In almost every programming language, a conditional structure has to be used to accomplish a
sophisticated task. In PHP, control structures are very similar to C++/Java control structures:
1- If/else/elseif Control structures:
After comparing two variables, there always has to be an action to be taken. For example
consider the following situation:
If A > B, display “A is Larger than B”
Or if A < B, display “A is smaller than B’
Else, display “A is equal to B”
To do this in PHP, we use IF/ELSE/ELSEIF structure:
Syntax:
if ( condition )
{
Statements;
}
elseif ( condition )
{
Statements;
}
else
{
Statements;
}
Please note that the first IF can never be omitted but the elseif, and/or else can be omitted if
necessary:
$a = 5;
$b = 3;
if ( $a > $b )
{
echo "A > B";
}
elseif ( $a < $b )
{
echo "A < B";
}
else
{
echo " A = B";
}
This program displays “A > B” when executed.
Take a look at the following program:
$a = 5;
$b = 3;
if ( $a > $b )
{
echo "A > B";
}
This program works just fine, but it will not display anything when A < B or A = B. This situation
may be useful when you, as a programmer, decide that those two situations never happen or you
do not care if they happen.
To include two or more conditions in IF clause, we use && or || operators. Consider the following
cases:
If A > B and C < D, display “Hi”,
If A > C or B < D, Display “Bye”
In PHP:
$a= 4;
$b = 3;
$c = 5;
$d = 9;
if ( $a > $b && $c < $d )
echo "hi";
if ( $a > $c || $b < $d )
echo “bye”;
This program displays: “hibye” when executed.
Other operators are displayed in the following table:
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical
TRUE if $a is equal to $b, and they are of the same type.
(introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical
TRUE if $a is not equal to $b, or they are not of the same type.
(introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b
Less than or
equal to
TRUE if $a is less than or equal to $b.
$a >= $b
Greater than or
equal to
TRUE if $a is greater than or equal to $b.
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
2- Switch/Case statements:
To compare many situations with more complex conditions, instead of IF/ELSE, Switch
statements can be used:
SYNTAX:
switch ( variable )
{
case value:
code;
break;
case value:
code;
break;
default:
code;
break;
}
Example:
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
Writing this with IF/ELSE statements, we have:
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
It is programmer’s decision when to use IF/ELSE and when to use SWITCH.
NOTE:
default statement works similar to else in IF/ELSE case.
Part 5: Looping structures and repeating an action:
In order to repeat an action, you have to use a special looping instruction. Looping instructions
are available in many flavors. Each flavor can only be used in a special case. For some
applications, all looping instructions can be applied, however, one should think about the
optimization and performance of the whole application before choosing the method.
1- For loops:
If you want to repeat a certain piece of code a limited and known number of times, you may use
FOR loops.
Syntax:
for ( start index, delimiter, increment)
{
Statements;
}
Example:
for ($i=0; $i<=10; $i++)
{
echo $i;
}
This piece of code outputs the following: 012345678910
The reason being is that, the FOR loop, starts from number zero and counts up to and including
number 10. Each time $i increments, the number in $i is displayed on the screen.
Obviously, FOR loop is the easiest loop to handle. FOR loops are used when the number of times
a loop has to be repeated is known, either directly, or stored inside another variable:
$delimiter = 10;
for ($i=0; $i<=$delimiter; $i++)
{
echo $i;
}
This code has exactly the same output as the first example.
Note that, FOR loops become inefficient as the number of delimiter grows.
For infinite loops, the following syntax is used:
for ( ;; )
This should never be used in a regular PHP program, otherwise the server load will be
dramatically increased and web server and your program will crash.
2- WHILE Loops:
While FOR loops become very inefficient as the number of delimiter grows, WHILE loops are
designed and preferred for loops that run more frequently.
For example, when the task is to read a file, WHILE loops are often used.
FOR loops simply become very inefficient when the size of the file grows. Also, it is sometimes
impossible to predict the size of an arbitrary file. Similarly, when an array of database records has
to be fetched, WHILE loops are used. Because the number of records to be read is not known
and with the growth of the records, FOR loops become slow and server resource intensive.
Generally, it is a good idea to use WHILE loops when iteration between elements is required.
Syntax:
while ( expression )
statement;
OR
while (expression):
statement;
...
endwhile;
Example:
$i = 1;
while ($i <= 10) {
echo $i;
}
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
Both programs are identical and they both display numbers from 1 to 10.
NOTE:
Depending on the condition (expression) in while loops, the statements may be executed or not.
3- Do/While loops:
Do/While loops are very similar to While Loops with the only difference that, in Do/While loops,
statements are executed at least once before the loop is terminated.
Syntax:
do {
statements;
}
while ( condition );
Example:
$i = 0;
do {
echo $i;
} while ($i > 0);
This loop executes exactly once and terminates. (why?)
Part 6: Functions and Argument passing
A function is a part of the code that is more often executed in the program. That is, when a piece
of code is often used to do an action, it can be turned into a function to increase the readability
and performance of the code.
For example, consider the following program:
1. Get number A
2. Get number B
3. Add them together
4. Add 4 to the results
5. Display the results
This program can easily be written in PHP. However, we will not implement the input functions:
<?
$A = 50;
$B = 20;
$temp_number = $A + $B;
$Result = $temp_number + 4;
Echo $Result;
?>
It is clearly noticed that this program can be broken into smaller pieces tied together:
1. Part that receives the numbers
2. Part that adds the numbers and adds 4 to the result
3. Part that displays the results
To implement such program, it is more convenient to use Functions.
Syntax:
function function_name ( parameters )
{
Function body
}
Example:
function add_numbers ( $A, $B )
{
$temp_number = $A + $B;
$Result = $temp_number + 4;
}
Note:
A function can be used without any parameters:
function say_hello ()
{
print “Hello!”;
}
This function prints “Hello!” when executed.
How to execute a Function:
When a function is defined, it can be executed easily by just calling its name with appropriate
arguments:
say_hello (); // Writes Hello!
Or
add_numbers ( 2, 3 ); // puts the value 9 in $ Result
Different types of Functions:
A function can be used to process information and store information without having any obvious
output to the program, or it can generate an output and pass it to the main program.
A function such as say_hello() or add_numbers ( $A, $B ) are both of type 1. These two functions
do not return anything directly to the program.
Warning:
add_numbers only modifies the contents of the $Result variable without returning anything to the
program.
To return the result to the calling program, return keyword is used:
function add_numbers ( $A, $B )
{
$temp_number = $A + $B;
$Result = $temp_number + 4;
return $Result;
}
In this case, the program will return the contents of the variable $Result to the calling program.
Functions of this type can be used with display codes, echo and print, to display the value
returned:
print add_numbers ( 3, 2 ); // displays 9 on screen
Scope of Variables:
When a variable is defined inside a function, it only lives as long as the function lives. That is,
when the function is executed, the variable is created inside the memory and when the function
finishes execution, the variable is destroyed. These types of variables are called Local variables.
On the other hand, a variable that lives throughout the execution of the program is called a global
variable.
In order to define a global variable in PHP, keyword global is used:
Syntax:
global variables;
Example:
global $number, $name;
Note:
Global variables take an extensive amount of memory. Use of global variables is not
recommended in most cases. Excessive usage of global variables is a sign of bad programming!
Default value of parameters:
Sometimes when a function is defined, the programmer may define a default value for any of the
variables used in case, the calling programmer does not pass a value:
Syntax:
function ( parameter = default value )
{
Statements;
}
Example:
function add_numbers ( $number1 , $number2=4 )
{
print $number1 + $number2;
}
add_numbers (2); // Prints 6 on display
Note:
Default value can not be specified for the first parameter.
Part 7: Using HTML to pass arguments to PHP files
So far we have discussed pure PHP scripts. It is now the time to explore how to embed a PHP
program into an HTML webpage to make a dynamic webpage.
Consider the following HTML form:
<form method="GET">
<p>First Name: <input type="text" name="fname" size="20"></p>
<p>Last Name: <input type="text" name="lname" size="20"></p>
<p><input type="submit" value="Submit" name="submit_button"></p>
</form>
We want to use this form to pass an argument to a PHP file. In other words, we want to take our
PHP file as a function to our HTML file!
Background:
In order to use this feature, we must know the basics of argument passing over the web.
Passing an argument on the web is usually accomplished by adding the argument to the URL.
For example, we want to pass “john” to variable “first_name” in script “names.php”. To do so, we
add “?” to the end of the URL to convey that we are passing an argument and we add each and
every argument one by one to the end of the “?” symbol:
names.php?first_name=john
This way, when we read the URL, we understand that our variable is “first_name” and the
parameter passed is “john”.
There are two basic methods to pass an argument using URL: POST method and GET method.
GET method is already discussed. In GET Method, parameters are added to the end of the URL,
hence they will be visible to everyone. Therefore it is less secure. Consider the case you want to
pass username and password to a script to validate. Last thing you may want to do is to let
everyone know what the username and password is!
In this case, we use POST method. In POST method, URL is not used to pass the arguments.
Instead, the variables are attached to the transmitting agent that will be sent to the server to
process. This way, it guarantees that information are not submitted more than once and also, the
fact that the transmitted data can be viewed by the recipient.
PHP can handle both GET and POST methods. To receive data transmitted by GET method,
either of these codes can be used:
$_GET[‘variable_passed’];
$HTTP_GET_VARIABLES[‘variable_passed’];
For POST method,:
$_POST[‘variable_passed’];
$HTTP_POST_VARIABLES[‘variable_passed’];
IMPORTANT:
Short forms of POST and GET methods ($_GET and $_POST) are preferred methods for
PHP parsers and compilers after PHP 5 was introduced. Short forms are still available
under older versions of PHP.
Examples:
<form method="GET">
<p>First Name: <input type="text" name="fname" size="20"></p>
<p>Last Name: <input type="text" name="lname" size="20"></p>
<p><input type="submit" value="Submit" name="submit_button"></p>
</form>
When this form is submitted:
<?
$fname = $_GET[‘fname’];
$lname = $_GET[‘lname’];
echo “Full name: “ . $fname . “ “ . $lname;
?>
<form method="POST">
<p>First Name: <input type="text" name="fname" size="20"></p>
<p>Last Name: <input type="text" name="lname" size="20"></p>
<p><input type="submit" value="Submit" name="submit_button"></p>
</form>
When this form is submitted:
<?
$fname = $_POST[‘fname’];
$lname = $_POST[‘lname’];
echo “Full name: “ . $fname . “ “ . $lname;
?>
There are several ways to implement a PHP script that can receive arguments from a HTML
page. A very popular method is to have separate HTML page and PHP script. The process is
done by the arguments passed from HTML page to another PHP script:
File: form.htm
<html>
<head></head>
<body>
<form method="POST" action="read.php">
<p>First Name: <input type="text" name="fname" size="20"></p>
<p>Last Name: <input type="text" name="lname" size="20"></p>
<p><input type="submit" value="Submit" name="submit_button"></p>
</form>
</body>
</html>
File: Read.php
<?
$fname = $_POST[‘fname’];
$lname = $_POST[‘lname’];
echo “Full name: “ . $fname . “ “ . $lname;
?>
The other method is, to use the same file pass and read the arguments. The trick is to pass the
argument to the SELF script (the file that writes the HTML form) using $_SERVER[PHP_SELF]:
File: Multi_purpose.php
<?
if ( $_POST[‘fname’] != “” || $_POST[‘lname’] != “” )
read_variables ( $_POST);
else
write_html ();
function write_html()
{
print ‘<html>
<head></head>
<body>
<form method="POST" action="<?=$_SERVER[PHP_SELF]?> ">
<p>First Name: <input type="text" name="fname" size="20"></p>
<p>Last Name: <input type="text" name="lname" size="20"></p>
<p><input type="submit" value="Submit" name="submit_button"></p>
</form>
</body>
</html>
‘;
}
function read_variables ( $post_vars )
{
$fname = $post_vars[‘fname’];
$lname = $post_vars [‘lname’];
echo “Full name: “ . $fname . “ “ . $lname;
}
?>
In this program we have used a conditional instruction to check the presence of “fname” and
“lname”. If these two variables were present, then we read them using a function and print the full
name. On the other hand, if these variables are not present, then we write the HTML form.
In HTML form, we have used the following piece of code: <?=$_SERVER[PHP_SELF]?>
As you can see, we have used <?= and ?> tags instead of usual PHP tags.
This special tag is equivalent to <? Print … ?> tag. This tag replaces the whole code with the
value of the string that follows “=” sign, in this case, $_SERVER[PHP_SELF].
Also, please note that using print instruction, we only write a full set of HTML codes. If print or
echo is followed by a single quote - ‘ -, everything inside this quote will be displayed as is.
However, if print or echo is followed by double quote, HTML will be displayed as is, and PHP will
be parsed.
If you have to transfer more than one variables, you can separate them using & sign:
i.e.
read.php?fname=john&lname=doe
Part 8: Using Sessions in PHP
Sessions are probably the most useful and effective way of securing a webpage. Session
uniquely identifies a single Browser's interaction with a single PHP based Site. In other words, a
session is a temporary logical connection between two nodes or computers on a network.
When you request a web page from a session enabled web site, server creates a session for your
browser. Throughout the time you are connected to that website, the server identifies you with the
session that is defined for your web browser. As soon as you close your web browser or lose
connection with the web server, the session is closed and the server no longer can identify you
with the same session number. This is essentially the basis of creating secure web sites.
To define a session in PHP, you must use session_start() on the very first line of your code,
before any other code in the page ( HTML or PHP ).
Syntax:
Session_start( void );
Example:
<?php
session_start();
?>
Now when you run the script, your browser is assigned with a PHP session ID.
To use sessions, you must be able to add variables to the session. To add global variables to an
already active session, session_register() is used.
Syntax:
session_register ( Variables );
You must be extra careful registering session variables as they are not usual variables in PHP.
For example, you want to register a variable $first_name with the current session. To do so, you
must get rid of “$” sign first and use the remaining as your session variable:
session_register (‘first_name’);
Example:
$barney = "A big purple dinosaur.";
session_register("barney");
To register more than one register with a session, you must register each variable individually.
In order to access the session variables, $_SESSION keyword is used.
Example:
<?
session_start();
print $_SESSION['barney']; // prints: A big purple dinosaur.
?>
IMPORTANT:
In PHP 5 and later, $_SESSION can be used without session_register. Also, note that, as of
PHP 5, session_register () cannot be used. All session variables should be handled by
$_SESSION.
Example:
<?
session_start();
$_SESSION['fname'] = “Joe”;
print “First name is: “ . $_SESSION['fname']; //prints: First name is: Joe
?>
When you are done with a session, you must either manually destroy it, or let the browser destroy
it. However, the most effective way is to destroy the session manually:
Syntax:
session_unregister();
If you have already defined variables with your current session, you can unset them at any time
using unset () instruction.
Syntax:
unset( variable );
Also note that in this case, variables are regular variables in PHP:
unset($barney);
Part 9: Using MySQL with PHP
So far we have introduced the PHP basics and HTML integration. A website usually needs a way
to store and retrieve information. There are two ways to store and retrieve data in PHP. The most
popular way is using a database, such as MySQL and the second way is using files. Files will be
discussed in part 10.
MySQL Review:
MySQL uses the standard SQL commands to insert and remove data into database tables. We
will review all the important SQL commands in this section:
1. “SELECT” Command: To read data from database, SELECT command is used.
Syntax:
SELECT columns FROM table_name ( WHERE column(s) {conditionals} ORDER BY
column {ASC | DESC} )
Part of the syntax inside the ( ) can be omitted.This part is used to narrow down the search and
ordering theresults.
Here are some examples:
1. Consider a simple database for a company:
Table name: employee_tbl
first_name last_name age email position
John Doe 26 John_doe@abc.com Manager
Jane Doe 28 Jane_doe@abc.com Employee
Foo Bar 25 Foo_bar@abc.com Sales
Peter Dutch 26 Peter_dutch@abc.com Employee
This table has 5 columns and 4 rows. Each row, as is seen from the table, is dedicated to only
one person.
To retrieve the information of all employees, we use SELECT command:
SELECT * FROM employee_tbl
We used “*” to indicate that we want to retrieve all the information.
If we just want to retrieve information about employees of 26 years old, we modify our command
to:
SELECT * FROM employee_tbl WHERE age=26
This will just chooses 2 rows.
Comparison operators can be used along with MySQL commands:
SELECT * FROM employee_tbl WHERE age<=28
This will choose 3 rows.
To order the rows chosen in a specific order, we can use ORDER BY directive:
SELECT * FROM employee_tbl ORDER BY age DESC
This will choose all the rows and order them according to age columns and in an descending
order.
SELECT * FROM employee_tbl WHERE age<=28 ORDER BY fname ASC
This will select 3 rows and sort them by the “fname” column in an ascending order.
2. “INSERT” Command: To insert data into database, INSERT command is used.
Syntax:
INSERT INTO table_name SET column1 = value1, column2=value2,…
Examples:
Consider the same table as before:
Table name: employee_tbl
first_name last_name age email position
John Doe 26 John_doe@abc.com Manager
Jane Doe 28 Jane_doe@abc.com Employee
Foo Bar 25 Foo_bar@abc.com Sales
Peter Dutch 26 Peter_dutch@abc.com Employee
We want to add another row to the end of the table:
First Name: John
Last Name: Ferry
Age: 29
Email: John_ferry@abc.com
Position: sales
Using INSERT command we have:
INSERT INTO employee_tbl SET first_name=John, last_name=Ferry, age=29,
email=John_Ferry@abc.com, position=sales
This will modify the table to:
first_name last_name age email position
John Doe 26 John_doe@abc.com Manager
Jane Doe 28 Jane_doe@abc.com Employee
Foo Bar 25 Foo_bar@abc.com Sales
Peter Dutch 26 Peter_dutch@abc.com Employee
John Ferry 29 John_ferry@abc.com Sales
3. “UPDATE” Command: To update an already inserted data in database, UPDATE
command is used.
Syntax:
UPDATE table_name SET field1=value1, field2=value2,… WHERE conditions
Example:
We want to change the age of Jane Doe to 27, without changing any other information:
UPDATE employee_tbl SET age=27 WHERE first_name=Jane AND last_name=Doe
As you can see, we have used AND keyword to make the distinction more accurate.
Here we give some more arbitrary examples of UPDATE command:
UPDATE employee_data SET salary=220000, perks=55000 WHERE title='CEO';
UPDATE employee_data SET salary=220000, perks=55000 WHERE title='CEO';
4. “DELETE” Command: To delete a complete row from database, DELETE command is
used.
Syntax:
DELETE FROM table_name WHERE conditions
Example:
We want to delete the last row from the employee_tbl:
DELETE FROM employee_tbl WHERE first_name = John
Please note that this is not a very accurate statement. This will remove any row that has
first_name=John. To be more accurate, you must integrate AND operator as a part of WHERE
conditions.
PHP and MYSQL:
In order to be able to use MySQL features in PHP, we first must connect to a database and select
a database. To do so, in PHP the following lines are used:
$databse_server = "database_server";
$db_username = "database_username";
$password = "password";
$databse = "database_to_be_selected";
//the data base to connect to
$dbh = mysql_connect ( $database_server, $db_username, $password ) or die mysql_error();
//Select specific Database to use
mysql_select_db ( $databse);
As you may have already noticed, these variable names are arbitrary and you may change them
according to your database information.
After a database has been selected, you may start running the statements. To run a statement in
PHP, you may define a query as is shown:
mysql_query (“Mysql_statement”);
Example:
mysql_query (“SELECT * FROM employee_tbl”);
Please note that this is just a query and does not fetch the rows from the database. This is a
statement to be executed using mysql_fetch_array() command:
Syntax:
mysql_fetch_array (mysql_query);
Example:
$results = mysql_query (“SELECT * FROM employee_tbl”);
mysql_fetch_array ($results);
This fetches only one row from the database and stops executing. If we want to fetch more than
one row, or a complete set of rows, we can use WHILE statement:
WHILE ( $a_row = mysql_fetch_array($results) )
{
Statements;
}
This fetches all the results and rows that are selected by the SELECT command. However, just
running the mysql_fetch_array is not useful. In order to use the actual data retrieved from the
databse, we must tell PHP what column we want to use.
For example, we have the following php/mysql statements:
$results = mysql_query (“SELECT * FROM employee_tbl WHERE age = 25”);
mysql_fetch_array ($results);
To fetch all the rows we run a while loop:
WHILE ( $a_row = mysql_fetch_array($results) )
{
Statements;
}
$a_row is the result of the mysql_fetch_array after each execution. To retrieve each column from
the $a_row, we add the column name to it, encapsulated by [‘ and ‘]:
print $a_row[‘first_name’]; // prints Foo
This can be used to retrieve all sorts of information from the database.
NOTE:
If you want to run a query which does not produce an output, such as DELETE or UPDATE
statements, you may use the following structure instead of Mysql_fetch_array:
if (@mysql_query($results))
{ successful_msg ;}
else { echo( mysql_error() ); }
exit;
This just runs the sql query without producing any outputs. Using this you can find out if any error
has occurred during the execution.
Part 10: Using Files in PHP
Incomplete
Part 11: Other useful codes in PHP
There are a few functions left to discuss. These functions are not critical functions of PHP, but
they are very useful in some occasions.
1. include () and include_once():
Sometimes when you write a webpage, you want to avoid writing the PHP code directly inside the
HTML to avoid clutter. In this case, you can use include() or include_once() to include the PHP
script at the execution time.
Syntax:
include (‘file_name’);
include_once (‘file_name’);
Example:
include (‘sql.inc.php’);
include_once (‘sql.inc.php’);
These two examples include the file “sql.inc.php” to the web page when the page is being
compiled and rendered.
The only difference between include and include_once is that, include will add a page no matter
how many more times it has already been added to the page, but include_once will only add the
page once.
2. require () and require_once():
require and require_once are identical to include and include_once respectively. The only
difference is that, if the file to be included was not found when using include or include_once, the
script will just generate an error message and continues with the rest of the script.
In require and require_once case, if the file was not found, the script will stop loading and
generates an error message.
Usually files that their function is critical to the whole script, are included in the page using require
or require_once.
Syntax:
require (‘file_name’);
require _once (‘file_name’);
Example:
require (‘sql.inc.php’);
require _once (‘sql.inc.php’);
3. empty() and isset():
Sometimes it is necessary to determine if a string is empty or is a variable is set. To check
whether a string is empty or not, we use empty () instruction:
Syntax:
empty ( variable or string );
Example:
$str = “test”;
if ( empty ( $str ) )
echo “Empty”;
else
echo “ Not empty”;
This can also be written:
$str = “test”;
if ( !empty ( $str ) )
echo “Not empty”;
else
echo “ Empty”;
These examples will produce “Not empty” when executed.
To find out if a string or a variable is set, we use isset command:
Syntax:
isset ( variable );
$set_var = “Yes!”;
if ( isset ( $set_var ) )
echo “variable is set”;
else
echo “variable is not set”;
This example will produce “variable is set” when executed.
These two commands can be used along with the session registers.