Вы находитесь на странице: 1из 130

PHP & MySQL

PHP - What is it / does it do?


PHP: PHP Hypertext Pre-processor
Programming language that is interpreted and executed on
the server
Intermediate bytecode interpreted by runtime engine
Execution is done before delivering content to the client
Contains a vast library of functionality that programmers can
harness
Executes entirely on the server, requiring no specific features
from the client
Supports efficient Garbage collection
PHP - What is it / does it do?
Static resources such as regular HTML are simply output to the
client from the server
Dynamic resources such as PHP scripts are processed on the server
prior to being output to the client
PHP has the capability of connecting to many database systems
making the entire process transparent to the client

Web Page Request Load PHP File

PHP Engine
Run Script
HTML Response PHP Results
User Web Server
How to install PHP
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then install PHP and
MySQL
History
Started as a Perl hack in 1994 by Rasmus Lerdorf
(to handle his resume), developed to PHP/FI 2.0
By 1997 up to PHP 3.0 with a new parser engine
by Zeev Suraski and Andi Gutmans
Current version: 7
php is one of the premier examples of what an
open source project can be
Unique Features
Performance:
Portability:
Ease of Use
Open Source
Community Support
Third Party Application Support
PHP - Syntax and Structure
PHP is similar to C
All scripts start with
<?php and with with ?>

Line separator: ; (semi-colon)

Code block: { //code here } (brace brackets)


White space is generally ignored (not in strings)
Simple Program: Hello World

Output
Comment
Comments are created using:
// single line quote
# This is also a single-line comment
/* Multiple line block quote */
// also used to leave out parts of a code line

<?php
$x = 5 /* + 15 */ + 5;
echo $x;
?>
What is a php file?
PHP files can contain text, HTML, CSS, JavaScript, and PHP
code
PHP code are executed on the server, and the result is
returned to the browser as plain HTML
PHP files have extension ".php"
Required Components
Operating System (Linux)
Webserver (usually Apache)
A database engine (such as MySQL)
PHP interpreter
PHP application for the Web:
the typical approach is to embed PHP code into one or more
standard HTML documents using special tags, or delimiters.

<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>
PHP Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive.

<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>
Escape Sequences

Complete Reference
PHP Frameworks
PHP Decision Making

Decision making or flow control is the process of determining


the order in which statements execute in a program
The special types of PHP statements used for making decisions
are called decision-making statements or decision-making
structures
Basic Decision Making

Decision making involves evaluating Boolean expressions (true /


false)
If($catishungry) { /* feed cat */ }
TRUE and FALSE are reserved words
Initialise as $valid = false;
Compare with ==
AND and OR for combinations
E.g. if($catishungry AND $havefood) {/* feed cat*/}
if Statement
Used to execute specific programming code if the evaluation of
a conditional expression returns a value of TRUE
The syntax for a simple if statement is: if
(conditional expression) statement;
Contains three parts:
the keyword if
a conditional expression enclosed within parentheses
the executable statements
if Statement
A command block is a group of statements contained within a
set of braces
Each command block must have an opening brace ( { ) and a
closing brace ( } )
Simple example :

if ($a < $b) {


print $a is less than $b;
}
else {
print $b is less than $a;
}
if .. else Statement
An if statement that includes an else clause is called an
if...else statement
An else clause executes when the condition in an
if...else statement evaluates to FALSE
The syntax for an if...else statement is :
if (conditional expression)
statement;
else
statement;
if .. else Statement

An if statement can be constructed without the else clause


The else clause can only be used with an if statement
$Today = " Tuesday ";
if ($Today == " Monday ")
echo " <p>Today is Monday</p> ";
else
echo " <p>Today is not
Monday</p> ";
Nested if and if .. else Statement

When one decision-making statement is contained within another


decision-making statement, they are referred to as nested
decision-making structures
if ($SalesTotal >= 50)
if ($SalesTotal <= 100)
echo " <p>The sales total is
between 50 and 100, inclusive.</p> ";
switch Statement
Control program flow by executing a specific set of statements
depending on the value of an expression
Compare the value of an expression to a value contained within a
special statement called a case label
A case label is a specific value that contains one or more
statements that execute if the value of the case label matches the
value of the switch statements expression
switch Statement
Consist of the following components :
The switch keyword
An expression
An opening brace
One or more case labels
The executable statements
The break keyword
A default label
A closing brace
switch Statement
The syntax for the switch statement is :
switch (expression) {
case label:
statement(s);
break;
case label:
statement(s);
break;
...
default:
statement(s);
break;
}
switch Statement
A case label consists of:
The keyword case
A literal value or variable name
A colon (:)
A case label can be followed by a single statement or multiple
statements
Multiple statements for a case label do not need to be
enclosed within a command block
switch Statement
The default label contains statements that execute when the
value returned by the switch statement expression does not
match a case label
A default label consists of the keyword default followed
by a colon (:)
Loop Statement
A loop statement is a control structure that repeatedly executes a
statement or a series of statements while a specific condition is
TRUE or until a specific condition becomes TRUE
There are four types of loop statements :
while statements
do...while statements
for statements
foreach statements
while Statement
Tests the condition prior to executing the series of statements at
each iteration of the loop
The syntax for the while statement is:
while (conditional expression) {
statement(s);
}
As long as the conditional expression evaluates to TRUE, the
statement or command block that follows executes repeatedly
while Statement
Each repetition of a looping statement is called an iteration
A while statement keeps repeating until its conditional
expression evaluates to FALSE
A counter is a variable that increments or decrements with each
iteration of a loop statement
In an infinite loop, a loop statement never ends because its
conditional expression is never FALSE

$Count = 1;
while ($Count <= 10) {

}
do .. while Statement
Test the condition after executing a series of statements then
repeats the execution as long as a given conditional expression
evaluates to TRUE
The syntax for the do...while statement is :
do {
statement(s);
} while (conditional expression);
do .. while Statement

do...while statements always execute once, before a


conditional expression is evaluated

$Count = 2;
do {
echo " <p>The count is equal to
$Count</p> ";
++$Count;
} while ($Count < 2);
for Statement
Combine the initialize, conditional evaluation, and update
portions of a loop into a single statement
Repeat a statement or a series of statements as long as a given
conditional expression evaluates to TRUE
If the conditional expression evaluates to TRUE, the for
statement executes and continues to execute repeatedly until the
conditional expression evaluates to FALSE
for Statement

Combine the initialize, conditional evaluation, and update


portions of a loop into a single statement
Repeat a statement or a series of statements as long as a given
conditional expression evaluates to TRUE
If the conditional expression evaluates to TRUE, the for
statement executes and continues to execute repeatedly until the
conditional expression evaluates to FALSE
foreach Statement

Used to iterate or loop through the elements in an array


Do not require a counter; instead, you specify an array expression
within a set of parentheses following the foreach keyword
The syntax for the foreach statement is :

foreach ($array_name as
$variable_name) {
statements;
}
foreach Statement
Example :

$DaysOfWeek = array(("Monday",
"Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday", "Sunday");
foreach ($DaysOfWeek as $Day) {
echo "<p>$Day</p>";
}
for Statement
Combine the initialize, conditional evaluation, and update
portions of a loop into a single statement
Repeat a statement or a series of statements as long as a given
conditional expression evaluates to TRUE
If the conditional expression evaluates to TRUE, the for
statement executes and continues to execute repeatedly until the
conditional expression evaluates to FALSE
What Is Function ?

In PHP we have two type of functions :

1) User-defined Function.

2) Built-in Function.

User-defined Function : is the function created by user .

Built-in Function : is the function created by PHP , and ready to use.

The real power of PHP comes from its functions.

We just talk about user defined function in this chapter


User-Defined Function
User-defined function is just a name we give to a block of code that can be executed
whenever we need it. This might not seem like that big of an idea, but believe me, when you
understand and use functions you will be able to save a ton of time and write code that is
much more readable!

A function will be executed by a call to the function.

You may call a function from anywhere within a page.

A function will be executed by a call to the function.

PHP function guidelines:

Give the function a name that reflects what the function does

The function name can start with a letter or underscore (not a number)
Create a PHP Function

Begins with keyword function and then the space and then the name of the
function then parentheses() and then code block {}

function functionName()
{
//code to be executed;
}
Create a PHP Function

We want our function to print out the company motto each time it's called,

so that sounds like it's a job for the echo command!

<?php
function myfunction()
{
echo This is the first function to me ";
}
?>

Note: Your function name can start with a letter or underscore "_", but not a number!
Call Function - Example

<?php
function myfunction()
{
echo Muneer Masadeh";
}
echo my name is ;
myfunction();
?>
Parameters Functions

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
function myfunction($par1, $par2 ,..)
{
echo This is the first function with parameters to me ";
}
?>
Parameters Functions

<?php
function myname($firstName)
{
echo my name is ". $firstName ;
}
?>
Parameters Functions Call

<?php
function myname($firstName)
{
echo my name is ". $firstName . "!<br />";
}
myname(kalid");
myname("Ahmed");
myname(laith");
myname(muneer");
?>
Parameters Functions - Call

<?php
function myname($firstName, $lastName)
{
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myname(Kalid", Ali");
myname("Ahmed", Samer");
myname(Wael", Fadi");
myname(Muneer", " Masadeh");
?>
Parameters Functions - Call

<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName(muneer ",".");
echo "<br>My family's name is ";
writeName(" Masadeh ",,");
echo <br>I am Dr in ";
writeName(CS Department ",!");
?>
Function Returning Values

In addition to being able to pass functions information, you can also have
them return a value. However, a function can only return one thing,
although that thing can be any integer, float, array, string, etc. that you
choose!
How does it return a value though? Well, when the function is used and
finishes executing, it sort of changes from being a function name into being
a value. To capture this value you can set a variable equal to the function.
Something like:
$myVar = somefunction();
Functions Returning Values Example

<?php
function mySum($numX, $numY)
{
return ($numX + $numY);
}
$myNumber = 0;
echo "Before call function, myNumber = ". $myNumber ."<br />";
// Store the result of mySum in $myNumber
$myNumber = mySum(3, 4);
echo "After call function, myNumber = " . $myNumber ."<br />";
?>
Function Returning Values Example

<?php
function factorial($number)
{
$ temp = 0;
if($number <= 1)
return 1;
$temp = $number * factorial($number - 1);
return $temp;
}
$ number = 4;
if ($number < 0)
echo "That is not a positive integer.\n";
else
echo $number . " factorial is: " . factorial($number);
?>
Function Returning Values Example

<?php
$n = 10;
echo " The sum is . sum($n) ;

function sum($a)
{
if ( $n <= 0 )
return 0;
else
return ($n + sum($n-1));
}
?>
Function returning arrays
function create_array($no)
{
for ($i=0;$i<$no;$i++)
{
$arr[]=$i;
}
return $arr;
}
Passing Variable to a function

You can pass a variable by Value to a function so the


function cant modify the variable.
You can pass a variable by Reference to a function so the
function can modify the variable.
Passing Variable By Value

<?php
$numX = 1;
function byvalue ($numX)
{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by value = ". $numX ."<br />";
?>
Passing Variable By Reference

<?php
function byreference (&$numX)
{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by Reference = ". $numX ."<br />";
?>
Passing Variable By Reference

<?php
function foo(&$var)
{
$var++;
}
$a=5;
echo foo($a); // $a is 6 here
?>
PHP Variable Scopes

The scope of a variable is the part of the script where the


variable can be referenced/used.
PHP has four different variable scopes:
local
global
static
parameter
Local Scope

A variable declared within a PHP function is local and can only be


accessed within that function:

<?php
$x=5; // global scope

function myTest()
{
echo $x; // local scope
}

myTest();
?>
Local Scope

The script above will not produce any output because the echo
statement refers to the local scope variable $x, which has not been
assigned a value within this scope.

You can have local variables with the same name in different functions,
because local variables are only recognized by the function in which they
are declared.

Local variables are deleted as soon as the function is completed.


Global Scope

A variable that is defined outside of any function, has a


global scope.

Global variables can be accessed from any part of the script,


EXCEPT from within a function.

To access a global variable from within a function, use the


global keyword:
Global Scope

<?php
$x=5; // global scope
$y=10; // global scope

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // outputs 15
?>
Global Scope

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.

The example above can be rewritten like this:


Global Scope

<?php
$x=5;
$y=10;

function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}

myTest();
echo $y;
?>
Static Scope

When a function is completed, all of its variables are


normally deleted. However, sometimes you want a local
variable to not be deleted.

To do this, use the static keyword when you first declare the
variable:
Static Scope

<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

?>
Static Scope

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.


Parameter Scope

A parameter is a local variable whose value is passed to the


function by the calling code.

Parameters are declared in a parameter list as part of the function


declaration:

<?php

function myTest($x)
{
echo $x;
}

myTest(5);

?>
Working with Forms
1. Creating a form
2. Accessing the submitted data
3. Common operations on forms
1 - Creating a form
Form - <form>
This element defines a form that is used to collect user input

<form action = ".."


method = "...">

...
</form>

action = URL
method = get | post

http://www.w3schools.com/tags/tag_form.asp
Text field - <input>
For single line text input:

<input type = "text"


name = "mytextfield"
value = "initial value"
size = "50"
maxlength = "50"/>

http://www.w3schools.com/tags/tag_input.asp
Password - <input>
For single line masked text input

<input type = "password"


name = "pwd"/>
Radio button - <input>
Single choice

Male: <input type = "radio" name = "gender"


value="Male"/>
Female: <input type = "radio" name =
"gender" value="Female"/>
Checkbox - <input>
Multiple choice

<input type = "checkbox"


name = "sailing"/>
Labelling
<form>
<input type="checkbox" name="a" value
"Bike"> I have a bike <br>
<input type="checkbox" name="a" value
"car"> I have a car <br>

</form>
Drop-down list
<select><option>
Single choice

<select name="country" size="1">


<option value="UK">United
Kingdom</option>
<option value="USA">United States of
America</option>
<option value="NK">North Korea</option>
<option value="BE">Belgium</option>
</select>
(multiple) selection list
<select><option>
Multiple choice

<select name="country[]" size="3"


multiple="multiple">
<option value="UK">United
Kingdom</option>
<option value="USA">United States of
America</option>
<option value="NK">North
Korea</option>
<option value="BE">Belgium</option>
</select>
Text area - <textarea>
For multiple line text input

<textarea name="myTextArea"
cols="30"
rows="5">
</textarea>

http://www.w3schools.com/tags/tag_textarea.asp
Hidden fields - <input>
To send information with the form

<input type="hidden"
name="hidden1"
value="Form example for demo"/>
Button - <input> or <button>
<input type="submit"
name="submitButton"
value="Submit Form"/>

<button type="submit"
name="submitButton">
SubmitForm
</button>
2 - How does one access the submitted data?
Using PHP
Data stored in a variable
Depends on submission method:
GET
POST
If POST, either:
$varName (requires special configuration)
$_POST['varName'] (recommended)
$HTTP_POST_VARS['varName']
If GET, use:
$_GET['varName']
Difference between GET &
POST
GET POST
Parameters remain in browser Parameters are not saved
history because they are part of in browser history.
the URL
Can be bookmarked.
Can not be bookmarked.
can send but the parameter Can send parameters,
data is limited to what we can including uploading files, to
stuff into the request line (URL). the server.
Safest to use less than 2K of More difficult to hack
parameters, some servers
handle up to 64K POST method used when
Easier to hack for script kiddies sending passwords or
GET method should not be other sensitive
used when sending passwords information.
or other sensitive information. Can not be cached
Can be cached
Two basic approaches
Approach 1
HTML form
PHP script to process it
Approach 2
PHP script containing the form and the processing script:
<form action =
"<?php echo $_SERVER['PHP_SELF']; ?>"
method="post">
Example: Approach 1
<html>
<body>

<form action="welcome.php" method="post">


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

</body>
</html>

After clicking the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The
form data is sent with the HTTP POST method.
welcome.php
<html> Using HTTP Post method
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
Using GET method
<html> welcome.php
<body> <html>
<body>
<form
action="welcome.php" Welcome <?php echo
method=get"> $_GET["name"]; ?><br>
Name: <input type="text" Your email address is:
name="name"><br> <?php echo
E-mail: <input type="text" $_GET["email"]; ?>
name="email"><br>
<input type="submit"> </body>
</form> </html>
</body>
</html>
GET vs. POST
Both GET and POST create an array (e.g. array( key => value,
key2 => value2, key3 => value3, ...)). This array holds key/value
pairs, where keys are the names of the form controls and
values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These
are superglobals,
$_GET is an array of variables passed to the current script via
the URL parameters.
$_POST is an array of variables passed to the current script via
the HTTP POST method.
When to use GET & POST
GET:
Information sent from a form with the GET method is visible
to everyone
GET also has limits on the amount of information to send. The
limitation is about 2000 characters.
It is possible to bookmark the page.
It may be used for sending non-sensitive data.
POST:
Information sent from a form with the POST method is
invisible to others.
no limits on the amount of information to send.
Developers prefer POST for sending form data.
Examples
Display content of $_POST
Display value of text input field
Display value of the hidden field
Display content of the text area
Display value(s) of (multiple) selection list
<?php
$name=$email=$website=$comment=$gender="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=test_input($_POST["name"]);
$email=test_input($_POST["email"]);
$website=test_input($_POST["website"]);
$comment=test_input($_POST["comment"]);
$gender=test_input($_POST["gender"]);
}
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
How to make required input
fields
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
3 - Common operations
1. Check existence
Has a variable been set?

if (isset($_POST['myCheckbox2']))
echo "Option 2 was selected";
else
echo "Option 2 wasn't selected.";
2. Check which button was
pressed
Same as above

if (isset($_POST['button1']))
echo "Button 1 was pressed";
elseif (isset($_POST['button2']))
echo "Button 2 was pressed";
else
echo "no button pressed";
3. Email data
$to = "m.rutter@napier.ac.uk";
$subject = "form data";
$body = "Country chosen by the user:
$_POST['country1'] ";

mail($to,$subject,$body);

Requires appropriate server configuration (this is not permitted


on the schools server).
4. Error checking
Ensure entered data is valid
Examples
Mandatory fields
Postcode format
Phone number format
Date format
etc
Variable scope
Six scope rules directed study
Built-in superglobal
Constants
Global (2 flavours)
Static
Local (by default)
Superglobals
$GLOBALS
$_SERVER
$_GET
$_POST
$_COOKIE
$_FILES
$_ENV
$_REQUEST
$_SESSION
PHP: Built-in Database Access
PHP provides built-in database connectivity for a wide range
of databases
MySQL, PostgreSQL, Oracle, Berkeley DB, Informix, mSQL, Lotus
Notes, and more
Starting support for a specific database may involve PHP
configuration steps
Another advantage of using a programming language that has
been designed for the creation of web apps.
Architecture diagram
High-Level Process of Using
MySQL from PHP
Create a database connection
Select database you wish to use
Perform a SQL query
Do some processing on query results
Close database connection
Request & Reply
Creating Database Connection
Use either mysql_connect or mysql_pconnect to create
database connection
mysql_connect: connection is closed at end of script (end of
page)
mysql_pconnect: creates persistent connection
connection remains even after end of the page
Parameters
Server- hostname of server
Username username on the database
Password password on the database
PHP for Database Access
Connect to the MySQL server
$connection = mysql_connect("localhost",
$username, $password);
Access the database
mysql_select_db("winestore", $connection);
Perform SQL operations
Disconnect from the server
mysql_close($connection);
Error Handling
All mysql_ functions return NULL (or false) if they fail.
Several functions are helpful in graceful failure
die(string) - halts and displays the string
mysql_errno() - returns number of error
mysql_error() - returns text of error
Error Handling examples
if (!($connection = mysql_connect("localhost",$name,$passwd)))
die("Could not connect");

function showerror()
{
die("Error " . mysql_errno() . " : " . mysql_error());
}

if (!(mysql_select_db("winestor", $connection)))
showerror();
Example 1: Connect PHP script
to a database- exam_seq1.php
<?php
$servername = "localhost";

// Create connection
$conn = mysql_connect($servername,'root');

// Check connection
if (!$conn) {
die("Connection failed: " . mysql_connect_error());
}
echo "Connected successfully";
?>
Example 3:
<?php
$host="localhost";
$user="root";

$db="test";

$conn=mysql_connect($host,$user);
//$conn = mysql_connect($servername,'root');

// Check connection
if (!$conn) {
die("Connection failed: " . mysql_connect_error());
}
echo "Connected successfully";
Selection of the database

This command instructs PHP to select the database stored in


the variable $database
If the script cannot connect it will stop executing and will
show the error message: Unable to select database.
Example 2:form_seq1.php
<?php
//Step1
$error="<h1> Problem Connecting database</h1>";
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");

?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
Building a Query
Directly
$query = 'select * from fruits';
Using input information
$winery = $_POST[fruits];
$query = select * from fruits where
winery=$apple;
Running a Query
mysql_query returns a result handle
$result = mysql_query($query, $connection)
mysql_num_rows indicates the number of rows returned
$num_rows = mysql_num_rows($result)
mysql_fetch_array creates array/hash of result
For ($n=0; $n<$num_rows;$n++)
$row = mysql_fetch_array($result)
Example 3:login
mysql_select_db($db);

if(isset($_POST['username']) and isset($_POST['password'])){


$username=$_POST['username'];
$password=$_POST['password'];

$sql="SELECT * FROM users WHERE username='$username' AND


password='$password'";
$res=mysql_query($sql);
$count=mysql_num_rows($res);

if($count==1){
echo "you have successfully logged in";
exit();
}
else{
echo "invalid login info";
exit();}
}

?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="login_new.php">
Username: <input type="text" name="username" /><br /><br
/>
Password: <input type="password" name="password" /><br
/><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>
Result of fetch_array
Contains both numeric and index tags
Values are duplicated
Example:
Query: select surname, city from customers;
Row: ( 0=>'Walker', surname=>'Walker', 1=>'Kent', 'city'=>'Kent'
);
Printing the Complete Row
By number
for ($i=0; $i<mysql_num_fields($result); $i++)
echo $row[$i] . " ";
By field
echo $row['surname'] . ' ' . $row['city'];
Example 4:exam_sql2.php
<?php
$error="<h1> Problem Connecting database</h1>";
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");

$sql="SELECT * from student";


$result=mysql_query($sql) or die("query failed: ".mysql_error());

echo "<table border='1'>";


echo "<tr>";
echo "<th>ID</th><th>Name</th><th>Email</th>";
echo "</tr>";

while($row=mysql_fetch_array($result)){
echo "<tr>";
echo
"<td>",$row['Id'],"</td><td>",$row['Name'],"</td><td>",$row['Email'],"</td>";
echo "</tr>";
}
output
Closing Database Connection
mysql_close() Closes database connection

Only works for connections opened with mysql_connect()


Connections opened with mysql_pconnect() ignore this call
Often not necessary to call this, as connections created by
mysql_connect are closed at the end of the script anyway
Updating Databases
SQL query:

$query=UPDATE fruit SET number=123 WHERE name=apple;

$res=mysql_query($query);
Example 5:exam_sql3.php
<?php

$error="<h1> Problem Connecting database</h1>";


$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");

$sql="UPDATE student SET Name='Supriya' where Id=1";


$result=mysql_query($sql) or die("query failed: ".mysql_error());

$sql="SELECT * from student";


$result=mysql_query($sql) or die("query failed: ".mysql_error());

echo "<table border='1'>";


echo "<tr>";
echo "<th>ID</th><th>Name</th><th>Email</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo
"<td>",$row['Id'],"</td><td>",$row['Name'],"</td><td>",$row['
Email'],"</td>";
echo "</tr>";
}

echo "</table>";

mysql_close($conn);
?>
Inserting into a Database

SQL Query:

$query=INSERT INTO fruit (name,number) VALUES


(Pears,102);

$res=mysql_query($query);
Example 6:exam_sql4.php
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");
$sql="INSERT INTO student(Id,Name,Email)
VALUES('3','AAA','aaa@gmail.com')";
$result=mysql_query($sql) or die("query failed: ".mysql_error());

$sql="SELECT * from student";


$result=mysql_query($sql) or die("query failed: ".mysql_error());
Output
Deleting Records
SQL Query:

$query=DELETE from fruit WHERE name=apple;

$res=mysql_query($query);
Example 7: exam_sql5.php
$conn = mysql_connect('localhost','root');
mysql_select_db("test") or die("$error");

$sql="DELETE from student WHERE Name='AAA'";


$result=mysql_query($sql) or die("query failed: ".mysql_error());

$sql="SELECT * from student";


$result=mysql_query($sql) or die("query failed: ".mysql_error());

Вам также может понравиться