Sie sind auf Seite 1von 157

PHP

PHP stands for PHP: Hypertext


Preprocessor
PHP is a server-side scripting language,
like ASP
PHP scripts are executed on the server

PHP supports many databases (MySQL,


Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, etc.)
PHP is an open source software

PHP runs on different platforms


(Windows, Linux, Unix, etc.)
PHP is compatible with almost all
servers used today (Apache, IIS, etc.)
PHP is easy to learn and runs efficiently
on the server side

Files end with the extension .php


All statements end with a
semicolon
White space is ignored

A PHP scripting block always starts with


<?php and
ends with
?>.
A PHP scripting block can be placed
anywhere in the document. rather than
the shorthand form.

XML Style
<?php
Short Style
<?

?>
?>

Script Style
<script language=php>
</script>

ASP Style
<%

%>

<?php
echo hello,$name.;
?>

\n
\r
\t
\\
\s
\

Linefeed
Carriage return
Horizontal tab
Backslash
Dollar sign
Double quote

<html>
<body>
<?php
//This is a comment
/*This
is a
commentblock*/
?>
</body>
</html>

Variables are used for storing a 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:
$var_name = value

Naming Rules:
prefixed

with a $
begin with letter or underscore
may contain only letters, number,
underscores
case sensitive

$distance
$a
descriptive
a
with $
$123abc
or
$x+y

valid
valid but not
not valid, must start
not valid, $ must be
followed by letter
underscore
not valid

<?php
$txt="Hello World!";
x=16;
?>

<?PHP
$firstname=jeeva;
echo $firstname;
?>

echo( );
allows you to send one or multiple
pieces of code, separated by commas

<?php
echo "<h2>PHP is fun!</h2>";
echo "I'm about to learn PHP!<br>";
?>

print( );
returns a value of TRUE or FALSE, if the
function was called successfully

<?php
$firstname=jeeva;
print $firstname;
?>

Strings
Integers
floating-point
Boolean
Array
Object

A string is a sequence of characters


<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>

An integers is a number without


decimals
<?php
$x = 5985;
var_dump($x);
?>

A floating point number is a number having


decimal point or having exponential form.
<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
?>

Booleans can be either TRUE or FALSE.


$x=true;
$y=false;

An array stores multiple values in a


single variable
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>

An object is a data types which stores


data and information on how to process
those information.

Operator
+
*
/
quotient
%
modulus

Description
Add
Subtract
Multiply
Divide and return
Divide and return

<?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
?>

Operator Description
==
Equal to
!=
Not equal to
> Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
=== Equal to and of the same type

<?php
$p = 10;
$q = 11;
$r = 11.3;
$s = 11;
echo ($q > $p);
echo ($q < $p);
echo ($q >= $s);
echo ($r <= $s);
echo ($q == $s);
echo ($q == $r);
?>

Operator
Description
&&
||
!

AND
OR
NOT

<?php
$price = 100;
$size = 18;
echo ($price > 50 && $size < 25);
echo ($price > 150 || $size > 75);
echo !($size > 10);
?>

Operator Description
+=
Add and assign
-=
Subtract and assign
*=
Multiply and assign
/= Divide and assign quotient
%= Divide and assign modulus
.=
Concatenate and
assign (strings only)

<?php
$count = 7;
$age = 60;
$greeting = 'We';
$count -= 2;
echo $count;
$age;
echo $age;
$greeting .= 'lcome!';
echo $greeting;
?>

Conditional statements in PHP are


used to perform different actions
based on different conditions.
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.

if (...else) statement - use this


statement if you want to execute a set
of code when a condition is true (and
another if the condition is not true)
switch statement - use this
statement if you want to select one of
many sets of lines to execute

The if statement is used to execute some


code only if a specified condition is
true.
Syntax
if (condition)
{

code to be executed if condition is


true;
}

<?php
$name=venkat";
if($name==venkat")
{
echo venkat become software
engineer";
}
?>

If....else statement to execute some code


if a condition is true and another code
if the condition is false.
Syntax
if (condition){
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

<?php
$name=hopes";
if($name==venkat")
{
echo venkat become software engineer";
}
else
{
echo "you enter name is wrong";
}
?>

If you want to execute some code if a


condition is true and then check
another condition and finally another
code if both conditions are false, use
the if...elseifelse statement.

Syntax
if( condition1 )
{
statement1;
}
elseif ( condition2 )
{
statement2;
}
else
{
statement3;
}

<?php
$name="sitra";
if($name=="hopes")
{
echo "hopes college";
}
else if($name=="sitra")
{
echo "you enter place is sitra";
}
else
{
echo "you enter wrong places";
}
?>

The switch statement to select one of many 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;

...

default:
code to be executed if n is different from all labels;
}

<?php
$position="dba";
switch($position)
{
case "member":
echo "Welcome Member";
break;
case "siteadmin":
echo "Welcome siteadmin";
break;

case "designer":
echo "Welcome Designer";
Break;
case "dba":
echo "Welcome dba";
break;
default:
echo "Welcome you all others ";
break;
}
?>

While statements
The while statement will execute a
block of code if and as long as a
condition is true.
Syntax
while (condition)
{ code to be executed;
}

<?php
$count=1;
while($count<=10)
{
echo "$count<br/>";
$count++;
}

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.
Syntax
do {
code to be executed;
} while (condition is true);

<?php
$counter=0;
do
{
$counter++;
echo "The number is " . $counter . "<br />";
}
while($counter<5);
?>

The for loop is used when you know in


advance how many times the script
should run.
Syntax

for (initialization; test condition;


increment/decrement)
{
code to be executed;
}

<?php
for($i=0;$i<5;$i++)
{
echo "welcome to php<br/>";
}
?>

There are two ways to do it:


The first way pulls out only the values
in the array.
In this example each time the loop
iterates, the value of the element is
assigned to $value.
You can use whatever variable name
you want.

Syntax
foreach($arrayName as $value)
{
statements;

<?php
$employeeAges;
$employeeAges["Lisa"]="28";
$employeeAges["Jack"]="16";
$employeeAges["Ryan"]="35";
$employeeAges["Rachel"]="46";
$employeeAges["Grace"]="34";
foreach($employeeAges as $key => $value)
{
echo "Name: $key, Age: $value <br />";
}
?>

Strlen()
The strlen() function returns the length of
a string.
Syntax
strlen(string)
Example
<?php
echo strlen(Raju);
?>

Strcmp()
The strcmp() function compares two
strings.
Syntax
strcmp(string1, string2);
Example
<?php
echo strcmp(Raj",Raj");
?>

Strrev()
The strrev() function reverses a string.
Syntax
strrev(string);
Example
<?php
echo strrev("Hello World!");
?>

Strtrim()
Remove leading and trailing whitespace from a string.
Syntax
trim(string,charlist);
Example
<?php
$str = ' a b c ';
echo trim($str);
// output 'a b c
?>

Substr()
Retrieves a section of strings.
Syntax
substr(string,start,length);
Example
<?php
$str = 'Welcome to nowhere';
echo substr($str, 3, 4);
//output: come
?>

Strtolower()
Lowercases a string.
Syntax
strtolower(string);
Example
<?php
$str = 'Yabba Dabba Doo';
echo strtolower($str);
// output: 'yabba dabba doo
?>

Strtoupper()
uppercases a string.
Syntax
strtoupper(string);
Example
<?php
$str = 'Yabba Dabba Doo';
echo strtoupper($str);
// output: 'YABBA DABBA DOO
?>

Round()
The round() function rounds a floating-point
number.
Syntax
round(number,precision,mode);
Example
<?php
echo(round(4.96754,2) . "<br>");
echo(round(7.045,2) . "<br>");
echo(round(7.055,2));
?>

Number_format()
The number_format() function formats a number with
grouped thousands.
Syntax
number_format(number,decimals,decimalpoint,separator) ;
Example
<?php
$num = 1999.9;
$formattedNum = number_format($num)."<br>";
echo $formattedNum;
$formattedNum = number_format($num, 2);
echo $formattedNum;
?>

A function is a block of statements that


can be used repeatedly in a program.
A user defined function declaration
starts with the word "function.
Syntax
function functionName() {
code to be executed;
}

function multiply($n1,$n2)
{
$product=$n1*$n2;
return $product;
}
$x=3;
$y=4;
$z=multiply($x,$y);
echo "$z";

The isset () function is used to check


whether a variable is set or not.
If a variable is already unset with
unset() function, it will no longer be set.
The isset() function return false if
testing variable contains a NULL value.

<?php
if(!isset($_POST['submit']))
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter your age: <input name="age" size="2">
<input type="submit" name="submit" value="Go">
<?
}
else
{
$input = $_POST['age'];
if($input < 27)
{
echo "You are young";
}
elseif($input == 27)
{
echo "The perfect age";
}
elseif($input > 27)
{
echo "You are old!";
}
}
?>

Definitions
Unlike strings, which hold a single value,
arrays hold a list of values, also called
elements. Each value can be a string,
number, or another array.
An array is a special variable, which can
hold more than one value at a time.
For each value in the list, there is a key
or index associated with it.

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] .
" and " . $cars[2] . ".";
?>

Indexed Arrays
Arrays with numeric keys
Associative Arrays
Arrays with named keys.
Multidimensional Arrays
Arrays containing one or more
arrays

use numbers as the keys, beginning at


zero.
To create an array use the array()
function:
$parties = array( Kennedy, Bush,
Perot, Demento, Hoffman,
Maharishi );

<?php
$places=array("ukkadam","lakshmi_mills","PS
G","HOPES
","KICE");
$places[0]="ukkadam";
for($x=0;$x<count($places);$x++)
{
echo "{$places[$x]}<br />";
}
//echo $places[0]. " " .$places[1];
?>

Use associated strings as keys.


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
$age=array("jeeva"=>32,"jaik"=>22,"
sudhar"=>25);
//echo "sudhar age is " . $age["sudhar"]
. "years old.";
echo $age["jeeva"];
?>

Arrays are useful because they can hold a great deal of


information.
You can also use multi-dimensional arrays which can
hold even more information.
Instead of holding simple strings or numbers as we
have been doing, we can create an array which holds
other arrays as values.
Multidimensional arrays work very similar to regular
arrays, except that each element has two indices
rather than one.
Pointing to a value in one of the secondary arrays
requires thought .

$red=array("r1","r2","r3","r4");
$green=array("g1","g2","g3","g4");
$blue=array("b1","b2","b3","b4");
$colrs=array("Red"=>$red,
"Green"=>$green,
"Blue"=>$blue);
print $colrs['Green'][0];

The PHP date() function is used to format a date and/or a time.


The PHP date() function formats a timestamp to a more
readable date and time.
Syntax
date(format,timestamp);
Timestamp: A timestamp is the number of seconds from jan 1,
1970 at 00:00.
A timestamp is a sequence of characters, denoting the date
and/or time at which a certain event occurred.

PHP has the ability to dynamically


generate the time and date.
<?php
Print time();
?>

Return date/time information of the current


local date/time
<?php
$date_array=getdate();
foreach($date_array as $key=>$val)
{
print "$key=$val<br/>";
}
?>

gettimeof day()
The gettimeofday() function returns the
current time.
<?php
// Print the array from gettimeofday()
print_r(gettimeofday());
?>

$b=time();
print date("m/d/y",$b)."<br/>";
print date("D,F jS",$b)."<br/>"; //D-mon FSeptember jS-21st
print date("l,F jS Y",$b)."<br/>"; //llowercase fullday, Y-year
print date("g:i A",$b)."<br/>";//g-12hours
format,A-Am or Pm
print date("r",$b)."<br/"; //RFC 822
formatted date; Mon, 21 Sep 2010 time
+200

we have created scripts consisting of a

single file, with all the code we need


included in that file.
When you develop a large site, you will
find that to be very inefficient

Include will only produce a warning


(E_WARNING) and the script will
continue.
The include() statement includes and
evaluates the specified file.
Syntax
include 'filename';

<?php
$color=green;
$fruit=apple;
?>

<?php
echo A $color $fruit;//A
include vars.php;
echo A $color $fruit;//A green Apple
?>

<?php
echo <b>.date(d-m-y).</b>;
?>

<?php
Echo <html><body bgcolor=silver>
Echo welcome to php<br>
Echo Today is:
Include(date.php);
Echo <br>Thank you
Echo </body></html>;
?>

Require will produce a fatal error


(E_COMPILE_ERROR) and stop the script.
The require() statement includes and
evaluates a specific file.
Require() results in a fatal error.
If you want a missing file to halt processing
of the page.
Syntax
require 'filename';

<?php
require prepend.php
require $somefile;
require (somefile.txt);
?>

<center><h2>ODD
Numbers</h2></center>
<hr size=2 />

$num=array(5,14,19,28,31,35,54,63);
echo "<b> Orginal Array:</b><br>";
foreach($num as $n)
echo "$n,";
echo "<br><br>";

<?php
echo "<b>Multiples of 7: </b><br>";
$num=array(5,14,19,28,31,35,54,63);
foreach($num as $n)
if($n%7==0)
echo "$n,";
?>

require("r1.html");
require("r2.php");
require("r3.php");

Several predefined variables in PHP are


"superglobals", which means that they
are always accessible, regardless of
scope - and you can access them from
any function, class or file without
having to do anything special.

$_GLOBALS

an array of all global


variables

$_SERVER

an array of server
environment variables

$_GET

an array of variables passed


to script using GET method

$_POST

an array of variables passed


to script using POST
methods

$_COOKIE

an array of cookie variables

PHP has four functions for using


external files:
include(

filename.inc )
include_once( filename.inc )
require( filename.inc )
require_once( filename.inc )

When creating your HTML forms, three


things you will need to pay particular
attention to are:
field names
method
action

Every form field, whether its a text box,


radio button, select, even submit, must
have a name.
These names do not contain spaces. Nor do
they contain anything other than letters,
numbers, or underscores.
Name them something meaningful, because
the names you use in the forms are going to
become variables of the same name

GET sends the submitted data as a series of


name = value pair appended to the URL.
A benefit of GET is that it can be
bookmarked by the browser.
Drawbacks are GET is limited to how much
data can be sent, and it is less secure
because data is visible in the url.
$_GET is an array of variables passed to the
current script via the URL parameters.

<html>
<body>
<form action="get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo
$_GET["email"]; ?>
</body>
</html>

POST is more secure, the amount of data


than can be sent is much greater, but it
cannot be bookmarked by a browser.
$_POST is an array of variables passed to the
current script via the HTTP POST method.

<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>

<html>
<body>
Welcome <?php echo $_POST["name"]; ?
><br>
Your email address is: <?php echo
$_POST["email"]; ?>
</body>
</html>

GET METHOD
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.
The variables are displayed in the URL, it is possible to bookmark
the page.
POST METHOD
Information sent from a form with the POST method is invisible to
others.
It has no limits on the amount of information to send.
The variables are not displayed in the URL, it is not possible to
bookmark the page.

Action indicates the page to which data


will be sent.

It provides information about how to


open, read, and close a file on the
server.
fopen() is used to an open file.
fread() is used to read an open file.
fclose() is used to close an opened
file.

<?php
$myfile = fopen("webdictionary.txt",
"r") or die("Unable to open file!");
echo
fread($myfile,filesize("webdictionary.txt
"));
fclose($myfile);
?>

To allow users to upload files from a form.


Note

The enctype attribute of the <form> tag specifies


which content-type to use when submitting the
form. "multipart/form-data" is used when a form
requires binary data, like the contents of a file, to be
uploaded
The type="file" attribute of the <input> tag
specifies that the input should be processed as a
file. For example, when viewed in a browser, there
will be a browse-button next to the input field

<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>

A cookie is a small bit of information store


on a viewers computer by his or her web
browser by request from a web page.
The information is constantly passed in
HTTP headers between the browser and
web server; the browser sends the current
cookie as part of its request to the server
and the server sends update to the data
back to the user as part of its response.

The size of a cookie depends on the


browser but in general should not
exceed 1k(1,024 bytes)
Its use of shopping cart
A cookie is often used to identify a user.

cookie is a small file that the server


embeds on the user's computer
Each time the same computer requests
a page with a browser, it will send the
cookie too.

setcookie(name, value, expire, path,


domain, security);
Name - This sets the name of the cookie
and is stored in an environment variable
HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
Value - This sets the value of the named
variable and is the content that you
actually want to store

Expiry - This specify a future time in


second sine00:00:00 GMT on 1st jan
1970. After this time cookie will
become inaccessible. If this parameter
is not set then cookie will automatically
expire when the Web Browser is closed.

Path - This specifies the directories for


which the cooke is valid. A single
forward slash character permits the
cookie to be valid for all directories.
Domain - This can be used to specify
the domain name in very large domain
must contain at least two periods to be
valid. All cookies are only valid for the
host and domain which created them.

Security - This can be set to 1 to


specify that the cookie should only be
sent by secure transmission using
HTTPS otherwise set to 0 which mean
cookie can be sent by regular HTTP.

Create a cookies for a user name.

<?php
setcookie("user", "Alex Porter", time()
+3600);
?>

Retrieve the cookies value.


<?php
// Print a cookie
echo $_COOKIE["user"];
echo $HTTP_COOKIE_VARS["user"]."<br/>";
// A way to view all cookies
print_r($_COOKIE);
?>

Delete a cookies.

<?php
// set the expiration date to one hour
ago
setcookie("user", "", time()-3600);
?>

Using the isset function using the cookies.


<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!
<br />";
else
echo "Welcome guest!<br />";
?>

A PHP session solves this problem by


allowing you to store user information
on the server for later use (i.e.
username, shopping items, etc).
Session work by creating a unique
id(UID) for each visitor and store
variables based on this UID.
The UID is either stored in a cookie or is
propagated in the URL.

Session is a random string of 32


hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.

A PHP session is easily started by making


a call to the session_start() function.
Session variables are stored in
associative array called $_SESSION[].
These variables can be accessed during
lifetime of a session.
The session_start() must be appear
before the <html> tag

Starting a session.
<?php
// start session
session_start();
// register session variables
$_SESSION['name'] = 'Ronald';
$_SESSION['species'] = 'Rabbit';
?>

A PHP session can be destroyed by


session_destroy() function.
Destroy a single session variable using
unset() function to unset a session
variable

session_destroy() will reset your


session and you will lose all your stored
session data.
Here is the call which will destroy all
the session variables.
<?php
Session_destroy();
?>

The unset() function is used to free the


specified session variable.
<?php
Unset($_SESSION[counter]);
?>

PHP allows you to send e-mails directly


from a script.
Mail() function is common to send input
data from a web form to an email address.
PHP provides a convenient way to send
email with the mail() function.
Syntax
mail(to,subject,message,headers,paramet
ers);

Parameter

Description

To

Required specifies the receiver/receivers of the email

Subject

Required specifies the subject of the email. This


parameter cannot contain any new line characters

Message

Required Define the message to be sent. Each line


should separated F(/n) Lines
Should be not exceed 70 characters

headers

Optional specifies additional headers like form Cc and


Bcc The additional headers should be separated with
a CRLF (r/n

Parameters

Optional specifies an additional parameter to the send


mail program

<?php
$to="xyz@somdomain.com";
$subject="This is subject";
$message="This is simple text message.";
$header="from:abc@somedomain.com\r\n";
$retval=mail($to,$subject,$message,$header);
if($retval==true)
{
echo "message send successfully...";
}
else
{
echo "Message could not be sent..";
}
?>

<?php
$to="xyz@somedomain.com";
$subject="This is subject";
$message="<b> This is HTML message.</b>";
$message.="<h1>This is headline.</h1>";
$header="From:abc@somedomain.com\r\n";
$header="Cc:afgh@somedomain.com\r\n";
$header.="MIME-Version: 1.0\r\n";
$header.="Content-type: text/html\r\n";
$retval=mail($to,$subject,$message,$header);
if($retval==true)
{
echo "Message sent sucessfully..";
}
else
{
echo "Message could not be sent..";
}
?>

The default error handling in PHP is


very simple.
An error message with filename, line
number and a message describing the
error is sent to the browser.

Error handling using die() function


<?php
$file=fopen("welcome.txt","r");
?>

<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>

A DBMS is a software system that


allows users to define, create and
maintain a database and provides the
controlled access to the data
It helps in protecting and maintain the
database over a long period of time.

Introduction

MySQL is the database that used on


web and runs on server.
It is very fast, reliable and easy to use.
It is freely available on internet and
runs on number of platforms.

Table A table is a collection of related


data and it consists of rows and
columns.
Records A row is also called as
records/tuple represents a single,
implicity structured data item in a table.
Fields These are smallest unit of
information that you can access.

Primary and Foreign key Every


table have a primary key and ensure
uniqueness in the table, no two rows
can have the same key. The primary
key of one table may also appear in
other tables. The instance of the
column in the second table is referred
to as a foreign key.

<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error()); //open
the connection
mysql_select_db("sudhar",$conn); //selet the database is to use
if(mysql_connect)
{
echo successfully connected;
}
mysql_close($conn);//for closing the connection
?>

Syntax
Insert into table name (column name1,
column name2) values
(value1,value2);

<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error()); //open the connection
mysql_select_db("sudhar",$conn); //selet the database is to use
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$empid=$_POST['empid'];
$sql=mysql_query("INSERT INTO emp VALUES('firstname','lastname',empid)"); //execute
the statment
echo $sql;
if(mysql_query($sql,$conn))
{
echo "record inserted!";
}
else
{
echo "something went wrong";
}
?>

Syntax
SELECT column_name(s) FROM
table_name

<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo <br>;
}
?>

Syntax
SELECT column_name(s) FROM
table_name WHERE column_name
operator value

<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp WHERE
firstname=James);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo <br>;
}
?>

Syntax
SELECT column_name(s) FROM
table_name ORDER BY column_name(s)
ASC|DESC
The ORDER BY keyword sorts the records
in ascending order by default.
If you want to sort the records in a
descending order, you can use the DESC
keyword.

<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(SELECT * FROM emp ORDER BY age);
while($row=mysql_fetch_assoc($query))
{
echo $row[firstname] . .$row[lastname];
echo $row[age];
echo <br>;
}
?>

Syntax
UPDATE table_name SET column1=value,
column2=value2,... WHERE
some_column=some_value

<?php
$conn=mysql_connect("localhost","root","")
or die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(UPDATE emp SET
age=25 WHERE firstname=james AND
lastname=miller);
?>

Syntax
DELETE FROM table_name WHERE
some_column = some_value

<?php
$conn=mysql_connect("localhost","root","") or
die(mysql_error());
mysql_select_db("sudhar",$conn);
$query=mysql_query(DELETE FROM emp WHERE
firstname=james);
?>

Das könnte Ihnen auch gefallen