INTRODUCTION TO PHP
PHP INTRODUCTION
PHP is a recursive acronym for “PHP: Hypertext
Preprocessor” -- It is a widely-used open source
general-purpose scripting language that is
especially suited for web development and can be
embedded into HTML.
PHP INTRODUCTION
> PHP is a server-side scripting language
> PHP scripts are executed on the server
> PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)
> PHP is open source software
> PHP is free to download and use
PHP INTRODUCTION
> PHP runs on different platforms (Windows, Linux,
Unix, etc.)
> PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
> PHP is FREE to download from the official PHP
resource: www.php.net
> PHP is easy to learn and runs efficiently on the
server side
PHP INTRODUCTION
Some info on MySQL which we will cover in the next
workshop...
> MySQL is a database server
> MySQL is ideal for both small and large
applications
> MySQL supports standard SQL
> MySQL compiles on a number of platforms
> MySQL is free to download and use
PHP INTRODUCTION
Instead of lots of commands to output HTML (as
seen in C or Perl), PHP pages contain HTML with
embedded code that does "something" (like in the
next slide, it outputs "Hi, I'm a PHP script!").
The PHP code is enclosed in special start and end
processing instructions <?php and ?> that allow
you to jump into and out of "PHP mode."
PHP INTRODUCTION
PHP INTRODUCTION
PHP code is executed on the server, generating
HTML which is then sent to the client. The client
would receive the results of running that script, but
would not know what the underlying code was.
A visual, if you please...
PHP INTRODUCTION
PHP GETTING STARTED
On windows, you can download and install WAMP.
With one installation and you get an Apache
webserver, database server and php.
http://www.wampserver.com
On mac, you can download and install MAMP.
http://www.mamp.info/en/index.html
PHP HELLO WORLD
Above is the PHP source code.
PHP HELLO WORLD
It renders as HTML that looks like this:
PHP HELLO WORLD
This program is extremely simple and you really did
not need to use PHP to create a page like this. All it
does is display: Hello World using the PHP echo()
statement.
Think of this as a normal HTML file which happens
to have a set of special tags available to you that do
a lot of interesting things.
PHP COMMENTS
In PHP, we use // to make
a single-line comment
or /* and */ to make a
large comment block.
PHP VARIABLES
> Variables are used for storing values, like text
strings, numbers or arrays.
> When a variable is declared, it can be used over
and over again in your script.
> All variables in PHP start with a $ sign symbol.
> The correct way of declaring a variable in PHP:
PHP VARIABLES
> In PHP, a variable does not need to be declared
before adding a value to it.
> In the example above, you see that you do not
have to tell PHP which data type the variable is.
> PHP automatically converts the variable to the
correct data type, depending on its value.
PHP VARIABLES
> A variable name must start with a letter or an
underscore "_" -- not a number
> A variable name can only contain alpha-numeric
characters, underscores (a-z, A-Z, 0-9, and _ )
> A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with an underscore ($my_string) or with
capitalization ($myString)
PHP CONCATENATION
> The concatenation operator (.) is used to put two
string values together.
> To concatenate two string variables together, use
the concatenation operator:
PHP CONCATENATION
The output of the code on the last slide will be:
Ifwe look at the code you see that we used the
concatenation operator two times. This is because
we had to insert a third string (a space character), to
separate the two strings.
PHP OPERATORS
Operators are used to operate on values. There are
four classifications of operators:
> Arithmetic
> Assignment
> Comparison
> Logical
PHP OPERATORS
PHP OPERATORS
PHP OPERATORS
PHP OPERATORS
PHP CONDITIONAL STATEMENTS
> Very often when you write code, you want to
perform different actions for different decisions.
> You can use conditional statements in your code
to do this.
> In PHP we have the following conditional
statements...
PHP CONDITIONAL STATEMENTS
> if statement - use this statement to execute
some code only if a specified condition is true
> if...else statement - use this statement to
execute some code if a condition is true and another
code if the condition is false
> if...elseif....else statement - use this statement
to select one of several blocks of code to be
executed
> switch statement - use this statement to select
one of many blocks of code to be executed
PHP CONDITIONAL STATEMENTS
Thefollowing example will output "Have a nice
weekend!" if the current day is Friday:
PHP CONDITIONAL STATEMENTS
Use the if....else statement to execute some code
if a condition is true and another code if a condition
is false.
PHP CONDITIONAL STATEMENTS
Ifmore than one line
should be executed if a
condition is true/false,
the lines should be
enclosed within curly
braces { }
PHP CONDITIONAL STATEMENTS
The following example
will output "Have a nice
weekend!" if the current
day is Friday, and "Have
a nice Sunday!" if the
current day is Sunday.
Otherwise it will output
"Have a nice day!":
PHP CONDITIONAL STATEMENTS
Use the switch statement to select one of many
blocks of code to be executed.
PHP CONDITIONAL STATEMENTS
Forswitches, first we have a single expression n
(most often a variable), that is evaluated once.
The value of the expression is then compared with
the values for each case in the structure. If there is a
match, the block of code associated with that case is
executed.
Use break to prevent the code from running into
the next case automatically. The default statement
is used if no match is found.
PHP CONDITIONAL STATEMENTS
PHP ARRAYS
> An array variable is a storage area holding a
number or text. The problem is, a variable will hold
only one value.
> An array is a special variable, which can store
multiple values in one single variable.
PHP ARRAYS
Ifyou have a list of items (a list of car names, for
example), storing the cars in single variables could
look like this:
PHP ARRAYS
> However, what if you want to loop through the
cars and find a specific one? And what if you had not
3 cars, but 300?
> The best solution here is to use an array.
> An array can hold all your variable values under a
single name. And you can access the values by
referring to the array name.
> Each element in the array has its own index so
that it can be easily accessed.
PHP ARRAYS
In PHP, there are three kind of arrays:
> Numeric array - An array with a numeric index
> Associative array - An array where each ID key
is associated with a value
> Multidimensional array - An array containing
one or more arrays
PHP NUMERIC ARRAYS
> A numeric array stores each array element with a
numeric index.
> There are two methods to create a numeric array.
PHP NUMERIC ARRAYS
In the following example the index is automatically
assigned (the index starts at 0):
In
the following example we assign the index
manually:
PHP NUMERIC ARRAYS
In the following example you access the variable
values by referring to the array name and index:
The code above will output:
PHP ASSOCIATIVE ARRAYS
> With an associative array, each ID key is
associated with a value.
> When storing data about specific named values,
a numerical array is not always the best way to do it.
> With associative arrays we can use the values as
keys and assign values to them.
PHP ASSOCIATIVE ARRAYS
In this example we use an array to assign ages to
the different persons:
Thisexample is the same as the one above, but
shows a different way of creating the array:
PHP ASSOCIATIVE ARRAYS
PHP MULTIDIMENSIONAL ARRAYS
Ina multidimensional array, each element in the
main array can also be an array.
And each element in the sub-array can be an array,
and so on.
PHP MULTIDIMENSIONAL ARRAYS
PHP MULTIDIMENSIONAL ARRAYS
PHP MULTIDIMENSIONAL ARRAYS
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 lines in a
script we can use loops to perform a task like this.
> In PHP, we have the following looping
statements:
PHP LOOPS
> while - loops through a block of code while a
specified condition is true
> do...while - loops through a block of code once,
and then repeats the loop as long as a 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
PHP LOOPS - WHILE
The while loop executes a block of code while a
condition is true. The example below defines a loop
that starts with
i=1. The loop will
continue to run as
long as i is less
than, or equal to 5.
i will increase by 1
each time the loop
runs:
PHP LOOPS - WHILE
PHP LOOPS – DO ... WHILE
The do...while statement will always execute the
block of code once, it will then check the condition,
and repeat the loop while the condition is true.
The next example defines a loop that starts with
i=1. It will then increment i with 1, and write some
output. Then the condition is checked, and the loop
will continue to run as long as i is less than, or equal
to 5:
PHP LOOPS – DO ... WHILE
PHP LOOPS – DO ... WHILE
PHP LOOPS - FOR
PHP LOOPS - FOR
Parameters:
> init: Mostly used to set a counter (but can be
any code to be executed once at the beginning of
the loop)
> condition: Evaluated for each loop iteration. If it
evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
> increment: Mostly used to increment a counter
(but can be any code to be executed at the end of
the loop)
PHP LOOPS - FOR
The example below defines a loop that starts with
i=1. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the
loop runs:
PHP LOOPS - FOR
PHP LOOPS - FOREACH
For every loop iteration, the value of the current
array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
PHP LOOPS - FOREACH
The following example demonstrates a loop that
will print the values of the given array:
PHP LOOPS - FOREACH
Winner of the most impressive slide award
PHP FUNCTIONS
> We will now explore how to create your own
functions.
> To keep the script from being executed when the
page loads, you can put it into a function.
> A function will be executed by a call to the
function.
> You may call a function from anywhere within a
page.
PHP FUNCTIONS
A function will be executed by a call to the function.
> Give the function a name that reflects what the
function does
> The function name can start with a letter or
underscore (not a number)
PHP FUNCTIONS
A simple function that writes a name when it is
called:
PHP FUNCTIONS - PARAMETERS
Adding parameters...
> To add more functionality to a function, we can
add parameters. A parameter is just like a variable.
> Parameters are specified after the function
name, inside the parentheses.
PHP FUNCTIONS - PARAMETERS
PHP FUNCTIONS - PARAMETERS
PHP FUNCTIONS - PARAMETERS
This example adds
different punctuation.
PHP FUNCTIONS - PARAMETERS
PHP FORMS - $_GET FUNCTION
> The built-in $_GET function is used to collect
values from a form sent with method="get".
> Information sent from a form with the GET
method is visible to everyone (it will be displayed in
the browser's address bar) and has limits on the
amount of information to send.
PHP FORMS - $_GET FUNCTION
Notice how the URL carries the information after the file name.
PHP FORMS - $_GET FUNCTION
The "welcome.php" file can now use the $_GET
function to collect form data (the names of the form
fields will automatically be the keys in the $_GET
array)
PHP FORMS - $_GET FUNCTION
> When using method="get" in HTML forms, all
variable names and values are displayed in the
URL.
> This method should not be used when sending
passwords or other sensitive information!
> However, because the variables are displayed
in the URL, it is possible to bookmark the page.
This can be useful in some cases.
> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
PHP FORMS - $_POST FUNCTION
> The built-in $_POST function is used to collect
values from a form sent with method="post".
> Information sent from a form with the POST
method is invisible to others and has no limits on the
amount of information to send.
> Note: However, there is an 8 Mb max size for the
POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
PHP FORMS - $_POST FUNCTION
And here is what the code of action.php might look like:
PHP FORMS - $_POST FUNCTION
Apart from htmlspecialchars() and (int), it should
be obvious what this does. htmlspecialchars()
makes sure any characters that are special in html
are properly encoded so people can't inject HTML
tags or Javascript into your page.
For the age field, since we know it is a number, we
can just convert it to an integer which will
automatically get rid of any stray characters. The
$_POST['name'] and $_POST['age'] variables are
automatically set for you by PHP.
PHP FORMS - $_POST FUNCTION
When to use method="post"?
> Information sent from a form with the POST
method is invisible to others and has no limits on
the amount of information to send.
> However, because the variables are not
displayed in the URL, it is not possible to bookmark
the page.
PHP - FILE INCLUSION
PHP allows us to create various elements and functions,
which are used several times in many pages.
PHP allows you to include file so that a page content can
be reused many times.
It is very helpful to include files when you want to apply
the same HTML or PHP code to multiple pages of a
website.
There are two ways to include file in PHP.
Include
Require
Both include and require are identical to each other,
except failure.
include only generates a warning, i.e., E_WARNING, and
continue the execution of the script.
require generates a fatal error, i.e., E_COMPILE_ERROR,
and stop the execution of the script.
ADVANTAGES OF FILE INCLUSION
Code Reusability: By the help of include
and require construct, we can reuse HTML
code or PHP script in many PHP scripts.
Easy editable: If we want to change
anything in webpages, edit the source file
included in all webpage rather than editing
in all the files separately.
PHP INCLUDE
PHP include is used to include a file on
the basis of given path.
Syntax
There are two syntaxes available for
include:
include 'filename '; Or
include ('filename');
Examples
Let's see a simple PHP include example.
File: menu.html
<a href="http://
www.javatpoint.com">Home</a>
<a href="http://www.javatpoint.com/php-
tutorial">PHP</a>
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-
tutorial">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
PHP REQUIRE
PHP require is similar to include, which is also
used to include files. The only difference is that it
stops the execution of script if the file is not
found whereas include doesn't.
Syntax
There are two syntaxes available for require:
require 'filename'; Or
require ('filename');
EXAMPLES
Let's see a simple PHP require example.
File: menu.html
<a href="http://www.javatpoint.com">Home</a>
<a href="http://www.javatpoint.com/php-
tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-
tutorial">HTML</a>
File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>
PHP AND MYSQL
MySQL is a relational database management
system based on the Structured Query Language,
which is the popular language for accessing and
managing the records in the database.
It is open-source database software, which is
supported by Oracle Company.
It is fast, scalable, and easy to use database
management system in comparison with Microsoft
SQL Server and Oracle Database.
MySQL supports many operating systems with
many languages like PHP, PERL, C, C++, JAVA, etc.
MySQL is very friendly with PHP, the most popular
language for web development.
BASIC DATABASE SERVER
CONCEPTS
Database runs as a server
Attaches to either a default port or an administrator
specified port
Clients connect to database
For secure systems
authenticated connections
usernames and passwords
Clients make queries on the database
Retrieve content
Insert content
SQL (Structured Query Language) is the language used
to insert and retrieve content
PHP MYSQL CONNECTION
PHP provides mysqli_connect() function to
open a database connection.
This function takes three parameters and
returns a MySQL link identifier on success or
FALSE on failure.
There are some MySQL functions for database
connectivity such as
mysqli_connection()
mysqli_select_db()
mysqli_query()
mysqli_result()
mysqli_close()
PHP MYSQLI_CONNECTION()
FUNCTION:
PHP mysqli_connect() function is used to connect
with MySQL database.
It returns resource if connection is established or
null.
Syntax of mysql_connection
connection mysqli_connect(server, user, password);
server:
Optional - The host name running database server. If
not specified then default value is localhost:3306.
User:
Optional - The username accessing the database. If
not specified then default is the name of the user that
owns the server process.
password :
Optional - The password of the user accessing the
database. If not specified then default is an empty
password.
PHP MYSQLI_SELECT_DB()
FUNCTION:
The mysqli_select_db() function sets the active
MySQL database.
This function returns TRUE on success, or FALSE
on failure.
mysqli_create_db() function attempts to create a
new database on the server associated with the
specified link identifier.
The mysqli_select_db() function is used to change
the default database for the connection.
Syntax of mysqli_select_db() function
mysqli_select_db(connection, name)
connection :Required. Specifies the MySQL
connection to use
name :Required. Specifies the database name
PHP MYSQL_QUERY() FUNCTION:
mysqli_query() Function performs a query against a
database.
This function selects a database and executes a query
on it.
If the optional link identifier isn't specified, the
function will try to find an open link to the MySQL
server and if no such link is found it'll try to create one
as if mysqli_connect() was called with no arguments.
The mysqli_query() sends a query to the currently
active database on the server that's associated with
the specified link identifier.
This function returns a resource identifier or FALSE if
the query was not executed correctly.
Syntax of mysqli_query() function
mysqli_query(database connection, Sql query);
Example:
$conn = mysqli_connect($host, $user, $pass,$dbname);
$sql = "CREATE DATABASE myDb";
mysqli_query($conn, $sql);
PHP MYSQL_RESULT() FUNCTION:
The mysqli_result() returns the contents of one
cell from a MySQL result set.
Syntax of mysqli_result() function
mysqli_result ($result , $row , $field);
result: The result resource that is being
evaluated. This result comes from a call to
mysqli_query().
row :The row number from the result that's
being retrieved. Row numbers start at 0.
field: The name or offset of the field being
retrieved.
MYSQL_CLOSE() Function
syntax
mysqli_close()
This function used to disconnect Mysql
database
EXAMPLE: CONNECT TO A
DBMS AND ACCESS DATABASE
<?php
$dbLocalhost = mysqli_connect("localhost", "root", "")
or die("Could not connect: " . mysqli_error());
mysqli_select_db(“student", $dbLocalhost)
or die("Could not find database: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
• die() stops execution of script if the database connection
attempt failed.
• mysqli_error() returns an error message from the previous
MYSQL operation.
READING FROM A
DATABASE
• We can now send an SQL query to
the database to retrieve some data
records.
resourceRecords = mysqli_query(query, resourceId);
• the resourceId is the one returned by mysqli_connect()
• the function returns a resource identifier to the returned data.
EXAMPLE: CONNECT TO A
DBMS, ACCESS DATABASE,
<?php SEND QUERY
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db(“student", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM stud", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
• the function will return a resource pointer (not the actual
data) to all the records that match the query.
• If all goes well, this script will output nothing on screen.
EXTRACT CONTENTS OF ONE
RECORD
• We can now extract the actual
data from the resource pointer
returned by mysql_query().
fieldData= mysql_result(resourceRecords, row, field);
• the resourceRecords is the one returned by mysql_query()
• field – database field to return
• the function returns the data stored in the field.
field
EXAMPLE: CONNECT TO A
DBMS, ACCESS DATABASE,
<?php SEND QUERY
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db(“student", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM stud", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
$strSurname = mysql_result($dbRecords, 0, "Surname");
echo "<p>$strSurname</p>";
?>
• the function will return a resource pointer (not the actual
data) to all the records that match the query.
• If all goes well, this script will output a surname on screen.
SQL STATEMENT
SELECT * FROM stud
• Go and obtain from the database
• every field
• FROM the
• stud table
SEPARATING THE DATABASE
CONNECTION
It is worth separating the database
connectivity from our scripts and
placing it in a separate file.
It provides a convenient means of moving your scripts from
•
one database platform to another.
EXAMPLE: SEPARATING THE
DATABASE CONNECTION
<?php
// File: database2.php
$strLocation = “Adama";
//$strLocation = “Addis Ababa";
if ($strLocation == "Home") {
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db(“student1",
student1 $dbLocalhost)
or die("Could not find database: " . mysql_error());
} else {
$dbLocalhost = mysql_connect("localhost", "username", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("student2",
student2 $dbLocalhost)
or die("Could not find database: " . mysql_error());
}
?>
• $strLocation could be easily switched between ‘Adama’ or ‘Addis Ababa’
VIEWING A WHOLE RECORD
To view the whole record returned
from mysql_query(), we need
another function...
array = mysql_fetch_row(resourceRecords)
• resourceRecords – resource identifier returned from
mysql_query().
• it returns an array containing the database record.
EXAMPLE: DISPLAYING ALL STUD
RECORDS
<?php
require_once("database2.php");
$dbRecords = mysql_query("SELECT * FROM stud", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrRecord = mysql_fetch_row($dbRecords))
mysql_fetch_row {
echo "<p>" . $arrRecord[0] . " ";
echo $arrRecord[1] . " ";
echo $arrRecord[2] . " ";
echo $arrRecord[3] . "</p>";
}
?>
• The function returns false when the last record is returned; thus, stopping
the loop.
LIMITING THE RECORDS
RETURNED
SELECT Surname FROM stud
• Retrieves only the Surname field from the table stud
SELECT * FROM stud LIMIT 3,4
• Select a certain number of records form a table
• 3 is the starting row
• 4 is the number of records to be selected after the starting
row
SEARCHING FOR MATCHING
RECORDS
SELECT * FROM stud WHERE sex=‘F’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a title of ‘Mr’ will be
returned.
SEARCHING FOR MATCHING
RECORDS
SELECT * FROM stud WHERE sex=‘F’
OR sex=‘M’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a title of ‘F’ or ‘M’
will be returned.
• we can also use AND and OR to formulate more
sophisticated conditions.
•
SEARCHING FOR MATCHING
RECORDS
SELECT * FROM stud WHERE sex=‘F’
AND Surname=‘Chala’ OR sex=‘M’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a surname of ‘Chala
and sex of ‘F’ or the sex of ‘M’ will be returned.
• we can also use AND and OR to formulate more
sophisticated conditions.
•
SORTING RECORDS
The ORDER BY attribute can be used to
sort the order in which records are
obtained.
SELECT * FROM stud ORDER BY Surname DESC
•the ORDER BY attribute is followed by the data field on which
to sort the record
• DESC or ASC – from high to low, or from low to high
Example15-12.php
ACCESSING MULTIPLE
<?php
TABLES
// File: example15-13.php
require_once("database2.php");
$dbRecords = mysql_query("SELECT * FROM stud WHERE sex = 'M'", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<p>Students:</p>";
while ($arrRecords = mysql_fetch_array($dbRecords)) {
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords[“sex"] . " ";
echo $arrRecords["Surname"] . " ";
echo $arrRecords["Firstname"] . "</p>";
}
//...continued...
Example15-13.php
ACCESSING MULTIPLE
TABLES
//continuation...
$dbRecords = mysql_query("SELECT * FROM course WHERE title= 'Web'", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<p>Products:</p>";
while ($arrRecords = mysql_fetch_array($dbRecords)) {
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords[“title"] . " ";
echo $arrRecords["Description"] . " ";
echo $arrRecords[“credithr"] . " ";
echo $arrRecords[“prerequest"] . "</p>";
}
?>
Example15-13.php
INSERTING RECORDS
How to create new database records
and insert them into a table?
INSERT INTO table (field1, field2,...) VALUES (‘value1’, ‘value2’,...)
• Alternatively, we have a simplified syntax:
INSERT INTO table VALUES (‘value1’, ‘value2’,...)
$dbProdRecords = mysql_query("INSERT INTO course
VALUES ( ‘Web Prog.', ‘Thought for grad class stud', ‘4',
‘Advanced Prog.')", $dbLocalhost)
Example15-15.php
INSERTING RECORDS
<?php
// File: example15-15.php
require_once("database2.php");
$dbcourseRecords = mysql_query("INSERT INTO course VALUES ( ‘Web Prog.',
‘Thought for grad class stud', ‘4', ‘Advanced Prog.')", $dbLocalhost)
or die("Problem writing to table: " . mysql_error());
$dbcourseRecords = mysql_query("SELECT * FROM products", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrcourseRecords = mysql_fetch_array($dbcourseRecords)) {
echo "<p>" . $arrcourseRecords [“title"] . " ";
echo $arrcourseRecords ["Description"] . " ";
echo $arrcourseRecords [“credithr"] . " ";
echo $arrcourseRecords [“prerequest"] . "</p>";
}
?>
Example15-14.php
Example15-15.php
DELETING RECORDS
How to delete database records from
tables?
DELETE FROM table WHERE field=‘value’
e.g.
$dbCustRecords = mysql_query("DELETE FROM stud
WHERE Id='3'", $dbLocalhost)
Note: If you have a relational database, you should tidy-up the other tables, based on
their connection with the record you’ve deleted.
DELETING RECORDS
How to delete database records from
tables?
DELETE FROM table
This will delete all records from a table!
Note: back-up your database first!
UPDATING RECORDS
How to modify the contents of an
existing database record?
UPDATE table SET field=‘value1’, field=‘value2’...WHERE
field=‘value’
•requires you to specify the table, the list of fields with their
updated values, and a condition for selection (WHERE).
Example15-18.php
UPDATING RECORDS
<?php
require_once("database2.php");
$dbCustRecords = mysql_query("UPDATE products SET Description='250 ml Tall
Glass' WHERE Id='6'", $dbLocalhost)
or die("Problem updating table: " . mysql_error());
$dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrProdRecords = mysql_fetch_array($dbProdRecords)) {
echo "<p>" . $arrProdRecords["Id"] . " ";
echo $arrProdRecords["Name"] . " ";
echo $arrProdRecords["Description"] . " ";
echo $arrProdRecords["Quantity"] . " ";
echo $arrProdRecords["Cost"] . "</p>";
}
?>
Example15-14.php
Example15-18.php
UPDATING RECORDS
How to modify the contents of an
existing database record?
UPDATE table SET field=‘value1’, field=‘value2’...WHERE
field=‘value’
Another Example:
$dbCustRecords = mysql_query("UPDATE products SET Name='Beer
and Lager Glass' WHERE Name='Beer Glass'", $dbLocalhost)
• A number of records will be updated in this example.
Example15-19.php
COUNTING THE NUMBER OF
RECORDS
How to count the number of records
after running a query?
$dbProdRecords = mysql_query("SELECT * FROM products",
$dbLocalhost)
or die("Problem reading table: " . mysql_error());
$intProductCount = mysql_num_rows($dbProdRecords);
•you can also use the same function to determine if a record
exists.
Example15-20.php
Example15-21.php
END OF CHAPTER 4
I Thank you