Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

PHP$SQL

PHP is a widely used open source scripting language that can be embedded within HTML to create dynamic web pages. PHP code is executed on the server and generates HTML that is sent to the browser. PHP can collect form data, add and modify data in databases, encrypt data, and control user access. Some basic PHP syntax includes opening and closing PHP tags <?php ?> to embed PHP code in HTML documents and using variables prefixed with $ to store and output data. Common PHP operations include conditional statements, loops, functions, and interacting with databases.

Uploaded by

Girma Tadese
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

PHP$SQL

PHP is a widely used open source scripting language that can be embedded within HTML to create dynamic web pages. PHP code is executed on the server and generates HTML that is sent to the browser. PHP can collect form data, add and modify data in databases, encrypt data, and control user access. Some basic PHP syntax includes opening and closing PHP tags <?php ?> to embed PHP code in HTML documents and using variables prefixed with $ to store and output data. Common PHP operations include conditional statements, loops, functions, and interacting with databases.

Uploaded by

Girma Tadese
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

INTRODUCTION PHP

• What is PHP?
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP files can contain3n text, HTML, CSS, JavaScript,
and PHP code
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP code are executed on the server, and the result
is returned to the browser as plain HTML
 PHP files have extension ".php“
What Can PHP Do?

• What Can PHP Do?

• PHP can generate dynamic page content


• PHP can create, open, read, write, delete, and close files
on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
PHP
• Basic PHP Syntax
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
example
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Comments in PHP
• Comments in PHP
• A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone
who is looking at the code
• <!DOCTYPE html>
<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 multiple
lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>
PHP Variables

• Variables are "containers" for storing information


• a variable starts with the $ sign, followed by the name of thevariable
• A variable name cannot start with a number
• Variable names are case-sensitive ($age and $AGE are two different
variables
• Example
• <?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
• When you assign a text value to a variable, put quotes around the value.
• : Unlike other programming languages, PHP has no command for
declaring a variable. It is created the moment you first assign a value to it
Data types
Variables can store data of different types
• PHP supports the following data types:
• Integers: are whole numbers, without a decimal point, like 4195.
• Doubles: are floating-point numbers, like 3.14159 or 49.1.
• Booleans: have only two possible values either true or false.
• NULL: is a special type that only has one value(a variable that
has no value assigned to it).
• Strings: are sequences of characters, like ‘Text string'
• Arrays: indexed collections of values.
• Objects: are instances of programmer-defined classes, which
can package up both other kinds of values and functions that are
specific to the class.
• Resources: are special variables that hold references to
resources external to PHP (such as database connections).
Php strings
• A string is a sequence of characters, like "Hello world!".
• Get The Length of a String
• The PHP strlen() function returns the length of a string
• <?php
echo strlen("Hello world!"); // outputs 12
?>
• Count The Number of Words in a String
• The PHP str_word_count() function counts the number of words in a string:
• <?php
echo str_word_count("Hello world!"); // outputs 2
?>
• Reverse a String
• The PHP strrev() function reverses a string:
• <?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
• Replace Text Within a String
• The PHP str_replace() function replaces some characters with some other characters in a string.
• The example below replaces the text "world" with "Dolly":
• <?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP Constants
• Constants are like variables except that once they
are defined they cannot be changed or undefined.
• A constant is an identifier (name) for a simple
value. The value cannot be changed during the
script.
• A valid constant name starts with a letter or
underscore (no $ sign before the constant name).
• Note: Unlike variables, constants are automatically
global across the entire script.
Syntax
• define(name, value, case-insensitive)
Php constants
• Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
• <?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
creates a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Operators

Operators are used to perform operations on variables and


values.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
PHP Assignment Operators

• PHP Assignment Operators


• The PHP assignment operators are used with
numeric values to write a value to a variable.
• The basic assignment operator in PHP is "=". It
means that the left operand gets set to the
value of the assignment expression on the
rightThe PHP assignment operators are used
with numeric values to write a value to a
variable.
Operator
PHP Arithmetic
Description
Operators
Example
A=10, B=20

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200


/ Divide numerator by denumenator B / A will give 2
% Modulus Operator and return remainder B % A will give 0
of an integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one
PHP Comparison Operators

• PHP Comparison Operators

• The PHP comparison operators are used to compare two values


(number or string): example

• //PHP Increment / Decrement Operators

• The PHP increment operators are used to increment a variable's


value.

• The PHP decrement operators are used to decrement a


variable's value
• example
PHP Conditional Statements

• Conditional statements are used to perform different actions based


on different conditions.
PHP - The if Statement
• The if statement executes some code if one condition is true.
• Syntax
• if (condition) {
    code to be executed if condition is true;
}
• <?php
$t = date("H");
if ($t < "20") {
    echo "Have a good day!";
}
?>
PHP - The if...else Statement

• The if....else statement executes some code if a condition is true and another code
if that condition is false.
• Syntax
• if (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}
• example
• <?php
$t = date("H");
if ($t < "20") {
    echo "Have a good day!";
} else {
    echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement

• The if....elseif...else statement executes different codes for more than two conditions.
• Syntax
• if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if this condition is true;
} else {
    code to be executed if all conditions are false;
}
• <?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!";
}
?>
PHP - The switch Statement

Use the switch statement to select one of several blocks of code to be


executed
• Syntax
• switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}
PHP - The switch Statement
• Example
• <?php
$favcolor = "red";

switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "green":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green!";
}
?>
Php loops
:

• Loops in PHP are used to execute the same block of code a specified number of times.
• 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
• The PHP while Loop
• The while loop executes a block of code as long as the specified condition is true
• Syntax
• while (condition is true) {
    code to be executed;
}
• <?php
$x = 1;

while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
}
?>
The PHP do...while Loop

• The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true
• do {
    code to be executed;
} while (condition is true);
• Example
<?php
$x = 1;

do {
    echo "The number is: $x <br>";
    $x++;
} while ($x <= 5);

?>
PHP for Loops

• The for loop is used when you know in advance how many times the script should run.
• Syntax
• for (init counter; test counter; increment counter) {
    code to be executed;
}
• 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>";
}
?>
The PHP foreach Loop

• The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
• Syntax
• foreach ($array as $value) {
    code to be executed;
}
• Example
• <?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


    echo "$value <br>";
}
?>
PHP Functions
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
• A user defined function declaration starts with the word "function":
• Syntax
• function functionName() {
    code to be executed;
}
• : A function name can start with a letter or underscore (not a number).
• Example

In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates
the beginning of the function code and the closing curly brace ( } ) indicates the end of the function.
The function outputs "Hello world!". To call the function, just write its name:
• Example
• <?php
function writeMsg() {
    echo "Hello world!";
}

writeMsg(); // call the function


?>
PHP Function Arguments

• Information can be passed to functions through arguments


• Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma
• <?php
function familyName($fname) {
    echo "$fname Refsnes.<br>";
}

familyName(“bekele");
familyName(“yani");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>.
PHP Functions - Returning values
• To let a function return a value, use the return statement: 
• Example
• <?php
function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
PHP Arrays
• ] What is an Array?
• An array is a special variable, which can hold more than one value at a time
• An array stores multiple values in one single variable
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
 PHP Indexed Arrays
• There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts at 0), like this:
• $cars = array("Volvo", "BMW", "Toyota");
• or the index can be assigned manually:
• $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
• Example
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array: 
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• or:
• $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
• The named keys can then be used in a script:
• Example
• <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Multidimensional Arrays

multidimensional array is an array containing one or more arrays
A

• multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three
levels deep are hard to manage for most people
• PHP - Two-dimensional Arrays
• A two-dimensional array is an array of arrays
• a three-dimensional array is an array of arrays of arrays.
• Example
• $cars = array
 (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
• For access s
• <?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
  );
PHP Forms

• The PHP superglobals $_GET and $_POST are used to collect form-data.
• The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.
• The most important thing to notice when dealing with HTML forms and PHP is that
any form element in HTML page will automatically be available to your PHP scripts.
• <html>
<body>

<form action=“hello.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
s

• The example HTML page above contains two input fields


and a submit button.
• When the user fills in this form and click on the submit
button, the form data is sent to the “hello.php" file.
• The “hello.php" file looks like this:
<html>
<body>
hello <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
PHP $_POST

• The $_POST variable is used to collect values


from a form with method="post".
• The $_POST variable is an array of variable
names and values are sent by the HTTP POST
method.
• Information sent from a form with the POST
method is invisible to others and has no limits
on the amount of information to send.
PHP $_GET…

• he $_GET variable is used to collect values from a form with method="get".


• The $_GET variable is an array of variable names and values are sent by the HTTP GET method.
Example
<form action=“hello.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
• When the user clicks the "Submit" button, the URL sent could look something like this:
localhost/hello.php?name=Gemechu&age=37
• The “hello.php" file can now use the $_GET variable to catch the form data
• Note that the names of the form fields will automatically be the ID keys in
the $_GET array:
– hello <?php echo $_GET["name"]; ?>.<br />
– You are <?php echo $_GET["age"]; ?> years old!
PHP $_GET…

• he $_GET variable is used to collect values from a form with method="get".


• The $_GET variable is an array of variable names and values are sent by the HTTP GET method.
Example
<form action=“hello.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
• When the user clicks the "Submit" button, the URL sent could look something like this:
localhost/hello.php?name=Gemechu&age=37
• The “hello.php" file can now use the $_GET variable to catch the form data
• Note that the names of the form fields will automatically be the ID keys in
the $_GET array:
– hello <?php echo $_GET["name"]; ?>.<br />
– You are <?php echo $_GET["age"]; ?> years old!
Introduction to SQL
• SQL is a standard language for accessing and manipulating databases.
• What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
Introduction to SQL
• RDBMS
• RDBMS stands for Relational Database Management
System.
• RDBMS is the basis for SQL, and for all modern
database systems such as MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.
• The data in RDBMS is stored in database objects called
tables.
• A table is a collection of related data entries and it
consists of columns and rows
Database Tables
A database most often contains one or more tables.
• ":Below is an example of a table called “student":

• Each table contains records (rows) with data.


• The table above contains three records (one
for each student) and three columns
(LastName, FirstName, age).
Connecting to a MySQL Database

• Before you can access and work with data in a database, you must
create a connection to the database.
• In PHP, this is done with the mysql_connect() function.
• Syntax
mysql_connect(servername,username,password);
• Parameter Description
– servername Optional. Specifies the server to connect to. Default value is
"localhost:3306"
– username Optional. Specifies the username to log in with. Default value is the
name of the user that owns the server process
– password Optional. Specifies the password to log in with. Default is ""
• Note: There are more available parameters, but the ones listed above
are the most important.
EXAMPLE
• In the following example we store the connection in a
variable ($con) for later use in the script.
• The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection

• The connection will be closed as soon as the script ends.


• To close the connection use the mysql_close() function.
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
Create a Database
• A database holds one or multiple tables.
• The CREATE DATABASE statement is used to create a database in MySQL.
• Syntax
CREATE DATABASE database_name
• To get PHP to execute the statement above we must use the mysql_query() function.
• This function is used to send a query or command to a MySQL connection.
• In the following example we create a database called "my_db":
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Create table
• The CREATE TABLE statement is used to create a database table in MySQL.
• Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
...
)
• We must add the CREATE TABLE statement to the mysql_query() function to
execute the command.
• Important: A database must be selected before a table can be created.
• The database is selected with the mysql_select_db() function.
• Note: When you create a database field of type varchar, you must specify
the maximum length of the field, e.g. varchar(20).
Create table
example
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con)){ // Create database
echo "Database created";
}
else {
echo "Error creating database: " . mysql_error();
}
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE student ( FirstName varchar(15), LastName varchar(15), Age int )";
mysql_query($sql,$con);S
mysql_close($con);
?>
SQL PRIMARY KEY

• The PRIMARY KEY uniquely identifies each record in a database table.


• Primary keys must contain UNIQUE values.
• A primary key column cannot contain NULL values.
• Most tables should have a primary key, and each table can have only
ONE primary key.
• CREATE TABLE student
(
S_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (S_Id)
)
SQL AUTO INCREMENT

• Auto-increment allows a unique number to be generated when a new record is


inserted into a table
• CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
• MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment
feature.
• By default, the starting value for AUTO_INCREMENT is 1, and it will increment by
1 for each new record
Insert Data Into database table

• The INSERT INTO statement is used to add new records to a database


table.
• Syntax
INSERT INTO table_name VALUES (value1, value2,....)
• You can also specify the columns where you want to insert the data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
• Note: SQL statements are not case sensitive.
– INSERT INTO is the same as insert into.
• To get PHP to execute the statements above we must use the
mysql_query() function.
• This function is used to send a query or command to a MySQL
connection.
EXAMPLE
• The following example adds two new records to the “Student" table:
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Student(FirstName, LastName, Age)
VALUES (‘Abebe', ‘Abera', '35')");
mysql_query("INSERT INTO Student (FirstName, LastName, Age)
VALUES ('Gelana', ‘Tolasa', '33')");
mysql_close($con);
?>
Insert Data From a Form Into a Database

• Now we will create an HTML form that can be used to add new
records to the "Student" table.

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
insert into form
• 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 mysql_query() function executes the INSERT
INTO statement, and a new record will be added to
the database table.
• Below is the code in the "insert.php" page
EXAMPLE
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO student(FirstName, LastName, Age)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
SQL SELECT Statement
• The SELECT statement is used to select data from a
database.
• The SELECT statement is used to select data from a
database.
• Syntax
SELECT column_name(s) FROM table_name
• To get PHP to execute the statement above we must
use the mysql_query() function.
• This function is used to send a query or command to a
MySQL connection
SQL SELECT Statement
• The following example selects all the data stored in the “Student" table
(The * character selects all of the data in the table):
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)S
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Student");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
SQL SELECT Statement
• The example above stores the data returned by the mysql_query()
function in the $result variable.
• Next, we use the mysql_fetch_array() function to return the first row from
the recordset as an array.
• Each subsequent call to mysql_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']).
• The output of the code above will be:
Abebe Yonas
Belachewu Kedir
Hana Temesgen
The ORDER BY Keyword

• The ORDER BY keyword is used to sort the data in a recordset.


• Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name
• The following example selects all the data stored in the “Student" table, and sorts the result
by the "Age" column:
<?php
$con = mysql_connect("localhost",“Gemechu",“pass456”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM studentDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>
Update Data In a Database

• The UPDATE statement is used to modify data in a


database table.
• Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
• To get PHP to execute the statement above we must
use the mysql_query() function.
• This function is used to send a query or command to
a MySQL connection.
Delete Data In a Database

• The following example updates some data in the


"Person" table:
<?php
$con = mysql_connect("localhost",Gemechu","pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Student SET Age = ‘36'
WHERE FirstName = ‘Abebe' AND LastName = ‘Yonas'");
mysql_close($con);
?>
example
• The DELETE FROM statement is used to delete records from a database table.
• Syntax
DELETE FROM table_name
WHERE column_name = some_value
• To get PHP to execute the statement above we must use the mysql_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 “strudent" table where
LastName=‘Yonas':
<?phpS
$con = mysql_connect("localhost",“Gemechu",“pass456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Student WHERE LastName=‘Yonas'");
mysql_close($con);

You might also like