PHP NOtes
PHP NOtes
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 a powerful tool for making dynamic and interactive Web pages quickly.
PHP costs nothing, it is free to download and use
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 easy to learn and runs efficiently on the server side
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
// PHP code goes here
?>
------------------------------------------------------------------------------------------------------------------------------------------
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function
"echo" to output the text "Hello World!" on a web page:
Khurasan University Page 1 of 55
Web Programming
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Note: PHP statements are terminated by semicolon (;).
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Comments are useful
for:
To let others understand what you are doing
To remind yourself what you did.
PHP supports three ways of commenting:
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
// This is a single line comment
# This is also a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
However; in PHP, all variables 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):
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
PHP Variables
Variables are "containers" for storing information. As with algebra, PHP variables can be used to hold
values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
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 ($y and $Y are two different variables)
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
------------------------------------------------------------------------------------------------------------------------------------------
After the execution of the statements above, the variable txt will hold the value Hello world!, the
variable x will hold the value 5, and the variable y will hold the value 10.5.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
------------------------------------------------------------------------------------------------------------------------------------------
In the example above there are two variables $x and $y and a function myTest(). $x is a global variable
since it is declared outside the function and $y is a local variable since it is created inside the function.
When we output the values of the two variables inside the myTest() function, it prints the value of $y as
it is the locally declared, but cannot print the value of $x since it is created outside the function.
Then, when we output the values of the two variables outside the myTest() function, it prints the value
of $x, but cannot print the value of $y since it is a local variable and it is created inside the myTest()
function.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=5;
$y=10;
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
------------------------------------------------------------------------------------------------------------------------------------------
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables
directly.
}
myTest();
echo $y; // outputs 15
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
------------------------------------------------------------------------------------------------------------------------------------------
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 Strings
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
------------------------------------------------------------------------------------------------------------------------------------------
PHP Integers
An integer is a number without decimals.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
Khurasan University Page 7 of 55
Web Programming
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed
with 0x) or octal (8-based - prefixed with 0)
In the following example we will test different numbers. The PHP var_dump() function returns the data
type and value of variables:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>
------------------------------------------------------------------------------------------------------------------------------------------
PHP Booleans
Booleans can be either TRUE or FALSE. Booleans are often used in conditional testing.
$x=true; $y=false;
PHP Operators:
The example below shows the different results of using the different arithmetic operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs 1.6666666666667
echo ($x % $y); // outputs 4
?>
------------------------------------------------------------------------------------------------------------------------------------------
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.
The example below shows the different results of using the different assignment operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
echo $x; // outputs 10
$y=20;
$y += 100;
echo $y; // outputs 120
$z=50;
$z -= 25;
echo $z; // outputs 25
$i=5;
$i *= 6;
echo $i; // outputs 30
$j=10;
$j /= 5;
echo $j; // outputs 2
$k=15;
$k %= 4;
echo $k; // outputs 3
?>
------------------------------------------------------------------------------------------------------------------------------------------
The example below shows the results of using the string operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!
$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>
------------------------------------------------------------------------------------------------------------------------------------------
The example below shows the different results of using the different increment/decrement operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=10;
echo ++$x; // outputs 11
$y=10;
echo $y++; // outputs 10
$z=5;
echo --$z; // outputs 4
$i=5;
echo $i--; // outputs 5
?>
Khurasan University Page 11 of 55
Web Programming
------------------------------------------------------------------------------------------------------------------------------------------
The example below shows the different results of using some of the comparison operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=100;
$y="100";
var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x !== $y);
echo "<br>";
$a=50;
$b=90;
The example below shows the different results of using the different array operators:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=1;
while($x<=5)
{
echo "The number is: $x <br>";
$x++;
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=1;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>
------------------------------------------------------------------------------------------------------------------------------------------
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.
This means that the do while loop would execute its statements at least once, even if the condition fails
the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$x=6;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>
------------------------------------------------------------------------------------------------------------------------------------------
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
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
} ?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value){
echo "$value <br>";
} ?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
Khurasan University Page 21 of 55
Web Programming
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
------------------------------------------------------------------------------------------------------------------------------------------
The following example has a function with two arguments ($fname and $year):
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function familyName($fname,$year)
{
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Ståle","1978");
familyName("Kai Jim","1983");
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function setHeight($minheight=50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}
PHP Arrays
An array stores multiple values in one single variable.
An array can hold many values under a single name, and you can access the values by referring to an
index number.
The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL supports standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
The data in MySQL is stored in tables. A table is a collection of related data, and it consists of columns
and rows.
PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the "Employees" table.
Syntax
mysqli_connect('Server_Name', ' User_Name', 'Password' , 'Database_Name');
OR
mysql_connect('Server_Name','User_Name','Password');
and connecting Database with
mysql_select_db('Database_Name');
Parameter Description
Server_Name Optional. Either a host/Server name or an IP address
User_Name Optional. The MySQL user name
Password Optional. The password to log in with
Database_Name Optional. The default database to be used when performing queries
Example-------------------------------------------------------------------------------------------------------------------------------
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
Close a Connection
The connection will be closed automatically when the script ends. To close the connection before, use
the mysqli_close() function:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
User this the following code while using local/testing server on your computer and then save it
in a connection.php file. Then import it in all web pages where required with the following code.
include("connection.php");
or
require_once("connection.php");
Example-------------------------------------------------------------------------------------------------------------------------------
Khurasan University Page 28 of 55
Web Programming
<?php
$server='localhost'; //Variable used for Server Name, default Server name is localhost in MySQL.
$user='root'; //Variable used for User name, default user name is root.
$pass=''; //Variable used for Password
$db='db_bcs'; //Variable used for Database Name, since our database name is db_bcs
Create a Database
The CREATE DATABASE statement is used to create a database table in MySQL.
We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.
The following example creates a database named "my_db":
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
-----------------------------------------------------------------------------------------------------------------------------------------
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns: "FirstName", "LastName"
and "Age":
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database engine
requires a value to locate the record.
The following example sets the PID field as the primary key field. The primary key field is often
an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added. To ensure that the primary key
field cannot be null, we must add the NOT NULL setting to the field:
Example-------------------------------------------------------------------------------------------------------------------------------
$sql = "CREATE TABLE Persons
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";
------------------------------------------------------------------------------------------------------------------------------------------
Text types:
Data type Description
Holds a fixed length string (can contain letters, numbers, and special characters). The
CHAR(size)
fixed size is specified in parenthesis. Can store up to 255 characters
Holds a variable length string (can contain letters, numbers, and special characters). The
VARCHAR(size) maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you
put a greater value than 255 it will be converted to a TEXT type
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If
a value is inserted that is not in the list, a blank value will be inserted.
ENUM(x,y,z,etc.)
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
Similar to ENUM except that SET may contain up to 64 list items and can store more
SET
than one choice
Number types:
Data type Description
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be
TINYINT(size)
specified in parenthesis
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits
SMALLINT(size)
may be specified in parenthesis
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number
MEDIUMINT(size)
of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum
Khurasan University Page 31 of 55
Web Programming
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative
to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a
negative number.
Date types:
Data type Description
A date. Format: YYYY-MM-DD
DATE()
Note: The supported range is from '1000-01-01' to '9999-12-31'
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS
DATETIME()
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
*A timestamp. TIMESTAMP values are stored as the number of seconds since the
Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS
TIMESTAMP()
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC
A time. Format: HH:MM:SS
TIME()
Note: The supported range is from '-838:59:59' to '838:59:59'
A year in two-digit or four-digit format.
YEAR() Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit
format: 70 to 69, representing years from 1970 to 2069
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or
UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
The second form specifies both the column names and the values to be inserted:
In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds two new
records to the "Persons" table:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
When a user clicks the submit button in the HTML form, in the example above, the form data is sent to
"insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added
to the "Persons" table.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Syntax
SELECT column_name(s)
FROM table_name;
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
The following example selects all the data stored in the "Persons" table (The * character selects all the
data in the table):
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
The example above stores the data returned by the mysqli_query() function in the $result variable.
Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array.
Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all
the records in the recordset. To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).
Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table
Khurasan University Page 35 of 55
Web Programming
The following example selects the same data as the example above, but will display the data in an HTML
table:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Firstname Lastname
Glenn Quagmire
Peter Griffin
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value;
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
The following example selects all rows from the "Persons" table where "FirstName='Peter'":
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
------------------------------------------------------------------------------------------------------------------------------------------
Peter Griffin
If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
The following example selects all the data stored in the "Persons" table, and sorts the result by the
"Age" column:
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
Glenn Quagmire 33
Peter Griffin 35
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
After the update, the "Persons" table will look like this:
Syntax
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.
The following example deletes all the records in the "Persons" table where LastName='Griffin':
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
------------------------------------------------------------------------------------------------------------------------------------------
With an ODBC connection, you can connect to any database, on any computer in your network, as long
as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:
1. Open the Administrative Tools icon in your Control Panel.
2. Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.
4. Click on Add in the System DSN tab.
5. Select the Microsoft Access Driver. Click Finish.
6. In the next screen, click Select to locate the database.
7. Give the database a Data Source Name (DSN).
8. Click OK.
Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.
The following example creates a connection to a DSN called northwind, with no username and no
password. It then creates an SQL and executes it:
Example-------------------------------------------------------------------------------------------------------------------------------
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
------------------------------------------------------------------------------------------------------------------------------------------
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns true if
it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
Example-------------------------------------------------------------------------------------------------------------------------------
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
------------------------------------------------------------------------------------------------------------------------------------------
An ODBC Example
The following example shows how to first create a database connection, then a result-set, and then
display the data in an HTML table.
Example-------------------------------------------------------------------------------------------------------------------------------
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body></html>
------------------------------------------------------------------------------------------------------------------------------------------
Connection Page:
PageName: Connection.php
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
//Syntax:
//mysql_connect('Server_Name','User_Name','Password');
//mysql_select_db('Database_Name''');
$server='localhost';
$user='root';
$pass='';
$db='bcsmorning';
Show Page:
PageName: show.php or any other name
This page is used to show records from your database tables.
SQL select query is used to extract records from database.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
//require_once("connection.php");
?>
<html > <body>
<?php
echo "<table width='100%' bgcolor='FFFFFF' border='1' align='center'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Address</th>";
Khurasan University Page 44 of 55
Web Programming
echo "<th>Class</th>";
echo "<th>Fee</th>";
echo "<th>Action</th>";
echo "</tr>";
while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
echo "<tr align='center'>";
echo "<td>".$id."</td>";
echo "<td>".$name."</td>";
echo "<td>".$address."</td>";
echo "<td>".$clas."</td>";
echo "<td>".$fee."</td>";
echo '<td><a href="delete.php?id='.$id.'"> Delete</a>
| <a href="update.php?id='.$id.'">Update</a></td>';
echo "</tr>";
}
echo "</table>";
?>
</body> </html>
------------------------------------------------------------------------------------------------------------------------------------------
Delete Page:
Page Name: delete.php or any other name.
This page is used to delete record from database table.
When someone click on delete link from show.php page, then specific record is deleted.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){
mysql_query("delete from tbl_student where id='$id'") or die("Query Error<br>".mysql_error());
header("location:show.php");
} ?>
------------------------------------------------------------------------------------------------------------------------------------------
Update Page:
Page Name: update.php or any other name.
This page is used to update specific record.
First create required fields in update.php page and give proper name to each filed.
When someone clicks on update link from update.php page, then specific record id is send to
update.php page, and that specific record is open in update.php page.
Following is the code of update.php page
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){
$sql=mysql_query("select * from tbl_student where id='$id'") or die("Query Error<br>");
while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
}
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$id=$_GET['id'];
$name=$_POST['name'];
$clas=$_POST['clas'];
$fee=$_POST['fee'];
$address=$_POST['address'];
mysql_query("update tbl_student
set
name='$name',
clas='$clas',
fee='$fee',
address='$address'
where id='$id'
") or die("Update Query Error");
header("location:show.php");
}
?>
<html >
<body>
<form name="form1" method="post" action="">
<table width="324" border="1">
<tr>
<td width="130">Name</td>
<td width="140"><input type="text" name="name"
value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="clas" value="<?php echo $clas; ?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="<?php echo $address; ?>"></td>
</tr>
<tr>
<td>Fee</td>
<td><input type="text" name="fee" value="<?php echo $fee; ?>"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" name="save"></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Insert Page:
Page Name: insert.php or any other name.
This page is used to insert data in database table.
Create required Fields in your Page according to your database table.
Create text boxes, dropdown lists, checkboxes, radio buttons, file fields etc using HTML
Give proper names to textboxes, dropdown lists, buttons etc.
Below is code of insert page
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
if(isset($_POST['save'])){
$name=$_POST['name'];
$clas=$_POST['clas'];
$address=$_POST['address'];
$fee=$_POST['fee'];
$gender=$_POST['gender'];
$country=$_POST['country'];
//-----Image/File------
$dir='images\std\ ';
$uploadfile=$dir.basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){
$filename='images/std/ '.$_FILES['file']['name'];
}
}
?>
<html >
<style>
.my{
font-family:Verdana, Geneva, sans-serif;
color:#FFF;
font-weight:bold;
text-decoration:underline;
font-size:11px
}
img {
border:none;
}
</style>
</head>
<body>
<table border="1" width="772" bgcolor="#CCCCCC">
<tr>
<td width="450" height="179" valign="top">
<form action="" method="post" enctype="multipart/form-data" name="form1">
<table width="100%" border="0">
<tr>
<td colspan="2" class="my"> Insert Student Record</td>
</tr>
<tr>
<td width="28%">Name</td>
<td width="72%"><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Class</td>
<td>
<?php
//this code is used to select data from Class table and show in drop down list.
$sql_class=mysql_query("select classname from tbl_class") or die("Error");
echo "<select name='clas'>";
while($row_class=mysql_fetch_array($sql_class)){
echo '<option>'.$row_class['classname'].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<?php
//this code is used to show inserted records.
while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$clas=$row['clas'];
echo "<tr align='center'>
<td>".$id."</td>
<td>".$name."</td>
<td>".$clas."</td>
<td><a href='details.php?id=".$row['id']."'>Details</a></td>
</tr>";
}
echo "</table>";
?>
</td>
</tr>
</table>
</body> </html>
------------------------------------------------------------------------------------------------------------------------------------------
Details Page
Page Name: details.php or any other name.
This page is used to show detail record of student.
When some click detail icon from insert.php page, then this page will open and show detail
record of student.
Example-------------------------------------------------------------------------------------------------------------------------------
<?php
include("connection.php");
$id=$_GET['id'];
if($_SERVER['REQUEST_METHOD']=='GET'){
while($row=mysql_fetch_array($sql)){
$id=$row['id'];
$name=$row['name'];
$address=$row['address'];
$fee=$row['fee'];
$clas=$row['clas'];
$image=$row['image'];
$country=$row['country'];
$gender=$row['gender'];
}
}
?>
<html>
<body>
</tr>
<tr>
<td>Gender</td>
<td>
<input
<?php if (!(strcmp($gender,'Male'))) {echo "checked";} ?>
type="radio" name="gender" value="Male"> Male
<input
<?php if ($gender=='Female') {echo "checked";} ?>
type="radio" name="gender" value="Female"> Female
</td>
</tr>
<tr>
<td>Country</td>
<td><input name="country" type="text" id="country" value="<?php echo $country; ?>"></td>
</tr>
<tr>
<td>Picture</td>
<td><img src="<?php echo $image; ?>" width="100" height="100" name="image"></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Searching:
Page Name: Create two pages and give names as:
search1.php
search2.php
First create criteria fields in search1.php page
And then write php searching code in search2.php page
<tr>
<td colspan="2">
<select name="select">
<option value="">--- Select any catagory ---</option>
<option value="id">ID</option>
<option value="name">Name</option>
<option value="class">Class</option>
</select>
</td>
</tr>
<tr>
<td width="36%"><input type="text" name="search" /></td>
<td width="64%"><input type="submit" name="btnsearch" value="Search" /></td>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
$select=$_POST['select'];
$search=$_POST["search"];
if($select=='')
{
echo "Please select any criteria";
}
else if($select=='id')
{
$sql=mysql_query("select * from tbl_student where id='$search'") or die("ID Query Error");
}
else if($select=='name')
{
$sql=mysql_query("select * from tbl_student
where name like '%$search%'")
or die("Name Query Error");
}
else if($select=='class')
{
$sql=mysql_query("select * from tbl_student where clas like '$search%'") or die("Class Query Error");
}
if(mysql_num_rows($sql)==0)
{
echo "No data found";
}
else {
echo '<tr>';
echo '<td>'.$id .'</td>';
echo '<td>'.$name .'</td>';
echo '<td>'.$clas .'</td>';
echo '<td>'.$fee .'</td>';
echo '<td>'.$address .'</td>';
}
echo '</table>';
}
?>
------------------------------------------------------------------------------------------------------------------------------------------