Sie sind auf Seite 1von 33

PHP MySQL

This page introduces PHP calls to MySQL and is the second half of the forms page of this document showing a display of available databases or database tables.

PHP MyAdmin
You can use PHP calls to MySQL to set up your database but there is an easier way. There is a tool called !PHP My"dmin!. #t ma$es it very easy to create the databese set up tables and fields. "fter the initial setup is done then # use PHP calls to MySQL to manage the database by retrieving values from it changing values or deleting entries. You can get more information at http%&&www.phpmyadmin.org.

PHP MySQL Calls


Most commonly used PHP calls to MySQL include%

bool mysql_create_db This function tries to create a new database associated with the optional resource lin$ identifier. The synta' is% bool mys(l)create)db* string database name + resource lin$)identifier,-. "n e'ample is% /status 0 mys(l)create)db*/dbname-.

mysql_connect 1 2pens a connection to the database. "n e'ample statement is% /chandle 0 mys(l)connect*!localhost! /dbuser /dbpass-.

mysql_select_db 1 Selects the database to be associated with the database handle *lin$ identifier- which is the second parameter passed to the function. "n e'ample statement is% /boolval0mys(l)select)db*/dbname /chandle- or die */dbname . ! 3atabase not found.! . /dbuser-.

QUERY Statement 1 The (uery statement is used to send (ueries to the database. The most commonly (ueries are S4L45T 34L4T4 6P3"T4 and #7S48T. #n my code #

used mys(l)db)(uery but this statement is depreciated. You should be able to use the statement mys(l)(uery without the database name string. 9ust remember that the (uery will be to the last selected database or last (ueried database. "n e'ample statement is% /result 0 mys(l)db)(uery*/dbname /(uery:- or die*!;ailed Query of ! . /(uery:-. This statement relies on the (uery statement provided above as !/(uery:!. There are several types of (ueries which can be performed using mys(l)db)(uery or mys(l)(uery. Some of the commonly used ones are.
o

Select 1 6sed to get information from the database. This statement will return the contents of all matching database entries. /(uery:0!select < from ! . /mainsection . ! as t: where t:.idname 0 ! . !=!! . /section> . !=! The variable !/mainsection! is the name of the table the delete operation will be performed on. The item t: is used to identify the database fields and idname is the name of one of the fields. The variable !/section>! is a string that the value in the idname field is to match in order to (ualify the database entry for retrieval into the result value when the (uery call is done. ?hen inside (uotes *!...!- use of =! is used to place a (uote in a (uery statement which is how this is used in the above statement.

Delete 1 6sed to remove a database entry. "n e'ample (uery statement using delete is% /(uery:0!delete from ! . /mainsection . ! where id 0 ! . /value. The variable !/mainsection! is the name of the table the delete operation will be performed on. The id is a database field used as a uni(ue identifier.

Update 1 6sed to change the value of a field one or more database entries. "n e'ample (uery statement using update is%

/newval 0 :. /(uery:0!update ! . /mainsection . ! set dbflag0! . /newval . ! where id 0 ! . /value. The variable !/mainsection! is the name of the table the delete operation will be performed on. The dbflag is a database field which is being set to a value of :.
o

nsert 1 6sed to add a new database entry to the database. "ny field value not specified here will be set to the default value for the field. "n e'ample (uery statement using insert is% /(uery:0!insert into ! . /mainsection . ! *url sitetitle description gifurl cat: email creator id entdate sitetype- values *=!! . /url . !=! =!! . /title . !=! =!! . /description . !=! =!! . /gifurl . !=! =!! . /category . !=! =!! . /email . !=! =!! . /uname . !=! ! . /i> . ! 5683"T4*- ! . /stype . !-!.

mysql_!etc"_ro# 1 6sed to get the results of a (uery row by row. "n e'ample is /thisrow0mys(l)fetch)row*/result-

The above statement will only return one row or returned database entry. The value returned is an array of field values in the database. The e'ample below will read all the returned rows and print the field names and values out.
while($thisrow=mysql_fetch_row($result)) { $i=0; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo $field_name . "=" . $thisrow $i! . "<"r#"; $i$$; % %

@ mysql_close 1 6sed to close the database. "n e'ample% mys(l)close*/chandle-.

PHP Control Statements

i!$ elsei!$ else


if ( ) { % elseif ( ) { % else { %

s#itc"
switch ( ) { case condition& "rea'; case condition( "rea'; %

#"ile
Synta'%
while (condition) { %

do
do { % while (condition)

!or
4'ample use of the for statement%
<)*h* for ( $n = &; $n < &0; $n$$) { echo "$n<+,#"; % )#

!oreac"

Aersions of PHP prior to version B do not support the foreach statement. The following code should list the contents of the array.
<)*h* $tree = array("trun'", ""ranches", "lea-es"); foreach ($tree as $*art) { echo ".ree *art/ $*art "; % )#

brea%
#s used to end the e'ecution of a for switch or while statement

contin&e
This statement is used to s$ip the rest of the current loop.
<)*h* for ( $n = &; $n < &0; $n$$) { echo "$n<+,#"; if ($n == 0) continue; echo ".his statement is s'i**ed when $n = 0.<+,#"; % )#

The continue statement can be given an optional parameter such as !continue >! telling it how many levels of loops to s$ip.

PHP E'ample
The code listed below is an e'ample showing how to embed PHP into an HTML file%
<1234.567 8.9: 6;+:<4 "=>>?@4>>2.2 8.9: A.0& .ransitional>>7B"# <html# <head# <meta htt*=equi-="4ontent=.y*e" content="teCt>html; charset=iso=DD0E=&"# <meta name="F7B7,G.3," content="Grachno*hilia @.E!"# <meta name="descri*tion" content="686 7Cam*le"# <meta name="'eywords" content="686 eCam*le"# <title#686 7Cam*le<>title# <lin' href="style.css" rel="stylesheet" ty*e="teCt>css"# <head# <"ody#

<h& style="teCt=aliHn/ center"#7Cam*le<>h&# <*# <) echo ".his is a test1"; )# <>*# <>"ody# <>html#

PHP E'ec&tion (rder


Server script programs such as Perl will run then the entire output is produced and sent to the client web browser. PHP does not e'ecute li$e this. PHP e'ecutes from the top to the bottom of the page and can be mi'ed with HTML. This is especially important to be aware of when trying to set coo$ies in PHP. The e'ample below shows PHP code being run based on a (uery string. " (uery string is a string that is appended to a url as follows% Ca href0!ctt.phpDfirstselection!E;irst SelectionC&aE The (uery string that the program will receive in this e'ample is !firstselection! and it is stored automatically in the PHP variable /Q648Y)ST8#7F. This e'ample will not show the HTML header. PHP code is shown in blue and HTML is shown in green. CDphp if */Q648Y)ST8#7F00!firstselection!G DE Ch:E;irst Selection ?as MadeC&h:E CDphp H if */Q648Y)ST8#7F00!secondselection!G DE Ch>ESecond Selection ?as MadeC&h>E CDphp H if */Q648Y)ST8#7F00!thirdselection!G DE ChIEThird Selection ?as MadeC&hIE CDphp H else

G DE CpEno selection was madeC&pE CDphp H DE #n this e'ample if the string is !firstselection! a header of type : is used to display the selection. #f the string is !secondselection! a header of type > is used to display the selection. #f no selection or an un$nown selection is made a paragraph is displayed stating that !7o selection was made!.

PHP (b)ects
PHP supports the creation of classes and obJects. " class can be created as follows%
class Guto { -ar $*osition = &; function mo-e ($distance) { $this=#*osition $= $distance; % function re*ort() { echo "6osition = " . (strinH) $this=#*osition . "<+,#"; % %

The obJect may be created as follows% /5ar 0 new "uto. Moving the car can be done with the following line% /5ar1Emove*B-.

PHP *ariable Re!erence


Aariables in PHP may be passed by reference. #f a variable is passed by reference the function it is being passed to can modify the variable. " variable reference is not the

same as a pointer they are symbol table aliases. ?hen a variable is passed by reference the reference sign !K! is only a part of the function definition. " variable may be passed to a function as follows% double */value:-. The function%
function dou"le (I$in-alue) { $in-alue $= $in-alue; %

PHP Array +&nctions


array*- 1 6sed to create an array asort*arsort*count*- 1 5ounts the number of array items. each*$sort*list*- 1 6sed to create an array ne't*- 1 Fet the ne't array element prev*- 1 Fet the previous array element rsort*sort*uasort*usort*u$sort*-

Array_m&ltisort +&nction
This function is used to sort multiple array entries. The e'ample below reads a database then uses a search string called /searchvalue to search through entries in the database for matches. #t uses the substr)count*function to count the number of matches. #t uses the array)multisort*function to sort the results.
array_multisort($matchscore, $desc, $id, $url);

This e'ample does not e'plain the use of the mys(l database functions in detail they are e'plained in more detail in later sections. The lines are also numbered for reference.
&. $query&="select J from " . $mainsection; entries in the data"ase >>select all

(. $result = mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); @. $nomatches=0; A. while($thisrow=mysql_fetch_row($result)) >>Het one row which is each entry for the section 0. { M. $matches=0; N. $urlmatches=su"str_count(strtolower($thisrow &!), $search-alue); >>url = &A0 D. $titlematches=su"str_count(strtolower($thisrow (!), $search-alue); >>title E. $descmatches=su"str_count(strtolower($thisrow @!), $search-alue); >>decri*tion &0. $matches=$urlmatchesJ@ $ $titlematchesJ0 $ $descmatches; &&. $matchscore $nomatches!=$matches; >>record the num"er of matches for each row in an array &(. $url $nomatches!=$thisrow &!; &@. $title $nomatches!=$thisrow $(!; &A. $id $nomatches!=$thisrow 0!; &0. $desc $nomatches!=$thisrow @!; &M. $nomatches$$; &N. % >>end while &D. array_multisort($matchscore, $desc, $id, $url); &E. for ($i0=$nomatches=&; $i0#=0; $i0==) >>Het one row which is each entry for the section (0. { (&. if ($matchscore $i0! # 0) ((. { (@. echo "<ta"le width=O"&00PO" cells*acinH=0 "order=0 cell*addinH=0 aliHn=O"centerO"#"; >>(MM (A. echo "<tr#<td width=O"E0PO" "Hcolor=O"QD0"0ffO" "ordercolor=O"Q0000D0O" nowra* -aliHn=O"to*O"#"; (0. echo "<font siRe=O"(O"#9atch ,an'=" . $matchscore $i0! . " <>font#<a href=O"$url $i0!O"#" . $title $i0! . " <>a#"; (M. echo "<>td#<>tr#"; (N. echo "<tr#<td width=O"E0PO" -aliHn=O"to*O"#"; (D. echo $desc $i0! . "<"r#"; >>descri*tion (E. echo "<font face=O"GrialO" siRe=O"(O"#<i#"; @0. echo "<>td#<>tr#<>ta"le#<"r#"; @&. % >>end if $matchscore @(. %

Line : sets up the (uery for the database. Line > reads the database. Line I initialiLes the counter that trac$s the number of matches. Line B reads individual rows of the (uery results until all rows are read. Lines M1N count the number of matches in each entry Line :O sets total match score which is weighed based on whether a match was found in the 68L title and&or description. Line :: creates and places values in the array /matchscore+, which is later used as a basis to sort the entries. Lines :>1:P sets array values based on the match score and database entries.

Line :Q performs the sort of the array based on the matchscore first. Line :N sets up a loop to display the arrays in reverse order since the array was sorted from lowest to highest value. Lines >>1I: display the matchstore rl url title and description.

PHP +&nctions !or *ariables


This section lists a few functions used to identify or create variables or constants. ;or more information see the PHP Manual.

define*!F844T#7F! !Hello!- 1 6sed to define constants and set their value. This e'ample defines the constant called F844T#7F with the string value !Hello!. 5onstant values cannot later be changed. gettype*/var- 1 8eturns the type of the variable as one of array boolean double integer string obJect resource or un$nown. is)long*/var- 1 8eturns a boolean value of true if the variable is an integer. is)double*/var- 1 8eturns a boolean value of true if the variable is a double. is)float*/var- 1 8eturns a boolean value of true if the variable is a float. is)int*/var- 1 8eturns a boolean value of true if the variable is an integer. is)string*/var- 1 8eturns a boolean value of true if the variable is a string. is)array*/var- 1 8eturns a boolean value of true if the variable is a double. is)obJect*/var- 1 8eturns a boolean value of true if the variable is an obJect.

ncl&din, PHP +iles


;iles that are included or re(uired are interpreted as HTML code unless the PHP beginning and end tags are present at the beginning and end of the file.

include*- 1 This statement is used to load and run a file at a set location only when the line the include statement is located on is e'ecuted. include)once*readfile*re(uire*- 1 8eplaces itself with the file with the name passed to the function. The file is read even if the line the re(uire function is on is not ever e'ecuted. re(uire)once*virtual*-

E'ample
#n most of my programs # li$e to $eep an include file that contains variables which may change. ;or e'ample when # interface to my SQL database # create variables that # can used to refer by number to my database fields. This way if # move a field in the database

or delete a field causing other field offset values to change # will only need to change my file that is included in all other files. Relow is the include statement in the code. CDphp include*!phpvars.inc.php!-. DE My phpvars.inc.php file contains%
<)*h* $sitename="9y Site"; $siteurl="htt*/>>www.mysite.com"; $urln=0; $sitetitlen=&; $descn=(; $a**ro-n=@; $acti-en=A;

)#

Usin, PHP #it" +orms


This page will provide an e'ample login form for authenticating to mys(l server. #t also establishes a user session and processes the results of the form. #t connects to the database server after the form has been submitted and shows a list of available databases for review. The section about sessions e'plains how that part of the code wor$s. The section called !MySQL 4'ample! has the code that allows the user to select a table in the database and display the contents of the table. The listing of the !dblist.php! file is shown in that section which is numbered as item :B. HereSs the code%
<)*h* session_start(); )# <1234.567 8.9: 6;+:<4 "=>>?@4>>2.2 8.9: A.0& .ransitional>>7B"# <html# <head# <meta htt*=equi-="4ontent=.y*e" content="teCt>html; charset=iso=DD0E=&"# <meta name="descri*tion" content="2ata"ase :oHin"# <title#2ata"ase :oHin<>title#

<>head# <"ody# <)*h* if ($su"mit) { $chandle = mysql_*connect("localhost", $username, $*assword) or die("4onnection Kailure to 2ata"ase"); $d"list = mysql_list_d"s($chandle); echo "<8@#G-aila"le 2ata"ases/<>8@#"; echo "<;:#"; while ($row=mysql_fetch_o"Tect($d"list)) { echo "<:<#<G href=O"d"list.*h*)", $row= #2ata"ase, "O"#", $row=#2ata"ase, "<>G#<+,#"; % echo "<>;:#"; session_reHister("location&"); session_reHister("username"); session_reHister("*assword"); $location&="data"ase"; mysql_close($chandle); % else { >> Korm has not "een su"mitted )# <8& style="teCt=aliHn/ center"#2ata"ase :oHin<>8&# <2<U style="teCt=aliHn/ center"# <form action="loHin.*h*" method="63S."# <ta"le# <tr# <td#:oHin Bame/<>td# <td#<in*ut ty*e="teCt" name="username" lenHth=&0 maClenHth="A0"#<>td# <>tr# <tr# <td#6assword/<>td# <td#<in*ut ty*e="*assword" name="*assword" lenHth=&0 maClenHth="A0"#<>td# <>tr# <tr# <td cols*an="(" aliHn="center"# <in*ut ty*e="su"mit" name="su"mit" -alue=":oHin"#<>td# <>tr# <>ta"le# <>form# <>2<U# <)*h* $sname=session_name(); % >> 7nd of else not $su"mit )#

<>"ody# <>html#

The /submit variable only e'ists after the form submission has been performed. Therefore this page is used both to produce the form and accept input from the form. " lin$ is provided for each file for every available database and the user can then select the lin$. The name of the database the user selected is provided after the (uestion mar$ D and is available in the 5F# variable Q648Y)ST8#7F. This is shown in the ne't file called dblist.php%

PHP Sessions
Sessions are used to compensate with the stateless condition of the HTTP protocol. ?ithout going into the technical details a session allows storage of information that is associated with the client for the duration of the clientSs visit. " session allows the storage of variables but not obJects. There is a uni(ue identification string for each session. HereSs how to implement a session using PHP. Place the following code at the very top of the HTML file which should now be a PHP file with a .php file e'tension% CDphp session)start*-. DE This code is re(uired for every file in which the session may be continued. #t must be placed before any HTML tag and even before any document type declaration such as% CT325TYP4 HTML P6RL#5 !1&&?I5&&3T3 HTML B.O: Transitional&&47!E ChtmlE Therefore if PHP and HTML are mi'ed the file may start li$e% CDphp session)start*-. DE CT325TYP4 HTML P6RL#5 !1&&?I5&&3T3 HTML B.O: Transitional&&47!E ChtmlE CheadE . .

Addin, *ariables to t"e Session

To add a variable to a session code similar to the following may be used% session)register*!location:!-. /location:0!database!. #f the value if /location: is printed in another file or location during the session the value of the variable !database! is printed. echo /location: !CR8E!.

settin, Coo%ies
Recause PHP e'ecutes code in se(uence along with HTML coo$ies must be set before the HTML header is sent. This is why the coo$ie must be set before the document type definition.
<)*h* session_start(); $ratinH&=$ratinH; session_destroy(); $today=time(); $atoday=Hetdate($today); >>Fet the date into an array $atoday=#mon$$; >>set the month to neCt month $month=$atoday=#mon; $year=$atoday=#year; if ($month # &() { $month=&; $year$$; % $ceC*ire=m'time(0,0,0,$month,&,$year); $lin'id=$L;7,5_S.,<BF; >>Het the lin' id num"er as an inteHer. Hlo"al $slin'id, $cname; $slin'id=str-al($lin'id); >>con-ert to a strinH $cname="test"; setcoo'ie($cname,$slin'id,$ceC*ire); )# <1234.567 8.9: 6;+:<4 "=>>?@4>>2.2 8.9: A.0& .ransitional>>7B"# <html# <head# <meta htt*=equi-="4ontent=.y*e" content="teCt>html; charset=iso=DD0E=&"# <meta name="F7B7,G.3," content="Grachno*hilia @.E"# <meta name="descri*tion" content="4om*uter .echnical .utorials ,ate 6aHe"# <title#4om*uter .echnical .utorials ,ate 6aHe<>title# <lin' href="style.css" rel="stylesheet" ty*e="teCt>css"# <>head# <"ody#

#n this e'ample the coo$ie is set to e'pire in one month. The name of the coo$ie is !test! and the coo$ie value is set to a lin$ #3 which is passed using a (uery string.

-ettin, Coo%ies
"ppropriate coo$ies for the web site domain are automatically received by PHP and are placed into PHP variables automatically. The isset*- function is used to test for their presence.
<)*h* Hlo"al $rated; $rated=0; if (isset($rate)) { echo "4oo'ie is set<"r#"; while (list ($name, $-alue) = each ($rate)) { echo "$name = $-alue<"r#On"; % % )#

The each*- function is used to get values from an array. The list*- function is used to assign a list of variables into an array all at one time. Therefore the line !while *list */name /value- 0 each */rate--! will increment through the /rate array getting the name of variables in the array with the value.

PHP Mail
The e'ample below shows how to send email.
$mailadd="testVmysite.com"; $mesaHe=".his is a test of usinH 686 to send email."; $headers .= "Krom/ <" . $mailadd . "#On"; $headers .= "W=Sender/ <" . $mailadd . "#On"; $headers .= "W=9ailer/ 686On"; >> mailer $headers .= ",eturn=6ath/ <" . $mailadd . "#On"; >> ,eturn *ath for errors $su"Tect=".est of 686 9ail sendinH"; mail($email, $su"Tect, $mesaHe, $headers);

The e'ample below shows how to read email from a mailbo' and chec$ the contents of the subJect line. #n this case someone has sent an email to the inbo' that we are reading. #f the email contains the string !updateDstr)#3! the code will determine this and get the #3 number to be updated. #t uses several string functions to do this so this e'ample is a good e'ample of using string functions.

& <)*h* ( $mailadd="su"missionsVmysite.com @ $mail*ass="*assword"; A $mailhand=ima*_o*en("{localhost>*o*@/&&0%<B+3W", $mailadd, $mail*ass); 0 if ($mailhand) M { N $msHqty=ima*_num_msH($mailhand); >>Het num"er of mail messaHes D for ($i(=&; $i(<=$msHqty; $i($$) >>,ead each messaHe E { &0 $header=ima*_header($mailhand,$i(); >>Fet the messaHe header && echo $header=#su"Tect . "<"r#"; &( $hd=strtolower($header=#su"Tect); >>4on-ert to lower case characters &@ if ($o*str=strstr($hd,"u*date)")) >>See if header contained the strinH "u*date)" &A { &0 $to' = strto' ($o*str," "); &M if ($o*str=strchr($to',")")) >>,eturns the strinH from the ")" until the end &N { &D $to'=su"str($o*str,&); >>Stri*s the ")", should now ha-e id &E $id=int-al($to'); >>4on-erts the <2 num"er to an inteHer (0 $newflaH=&; (& $query&="u*date " . $mainsection . " set u*date&=" . $newflaH . " where id = " . $id; (( mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); (@ ima*_delete($mailhand,$i(); (A echo $id . " mar'ed to "e u*dated."; (0 % (M % (N % (D ima*_eC*unHe($mailhand); >>delete mar'ed messaHes (E ima*_close($mailhand); >>&&@ @0 % @& else @( { @@ echo "canXt connect/ " . ima*_last_error(); @A % @0 )#

The list below is an e'planation of the lines% Line > 1 Sets the address of the mail bo'. Line I 1 Fets the password needed to read the mailbo' and ma$e changes. Line B 1 2pens the mailbo' returning a handle much li$e a file handle. Line P U IB 1 Regins an if statement that only runs if the mailbo' was opened successfully. This is because the returned value is 76LL if the

mailbo' was not opened. 5ode between line U and IB is run if the mailbo' was opened. Line M 1 Fets the number of mail messages in the mailbo'. Line Q N >M 1 This line cycles through each item in the mailbo'. Lines Q and >M define the code to be run for each mailbo' item. 5ode between brac$ets N and >M is run. Line :O 1 Fets the header of the mail message into a string. Line :: 1 3isplays the value of the message header. Line :> 1 5onverts the string to lower case characters. Line :I :B >U 1 Tests the converted header string to see if it contained the string !updateD!. #t returns the string starting at where the string !updateD! starts to the end of the searched string. #f the string !updateD! is found code between lines :B and >U is run. Line :P 1 Splits the string into words that were seperated by spaces in this case getting the string up to the end of the string. Line :U :M >P 1 8eturns the string from the !D! until the end. #f the returned valus is not 76LL code between lines :M and >P is run. Line :Q 1 Strips the !D! and returns the #3 as a string. Line :N 1 5onverts the #3 string to an integer. Lines >O1>B 1 6pdate values in an SQL database to reflect the fact that there is an update re(uest for a specific #3 number. Line >Q 1 3eletes messages that have been read. Line >N 1 5loses the mailbo'.

PHP MySQL
This page introduces PHP calls to MySQL and is the second half of the forms page of this document showing a display of available databases or database tables.

PHP MyAdmin
You can use PHP calls to MySQL to set up your database but there is an easier way. There is a tool called !PHP My"dmin!. #t ma$es it very easy to create the databese set up tables and fields. "fter the initial setup is done then # use PHP calls to MySQL to manage the database by retrieving values from it changing values or deleting entries. You can get more information at http%&&www.phpmyadmin.org.

PHP MySQL Calls


Most commonly used PHP calls to MySQL include%

bool mysql_create_db This function tries to create a new

database associated with the optional resource lin$ identifier. The synta' is% bool mys(l)create)db* string database name + resource lin$)identifier,-. "n e'ample is% /status 0 mys(l)create)db*/dbname-.

mysql_connect 1 2pens a connection to the database. "n e'ample statement is% /chandle 0 mys(l)connect*!localhost! /dbuser /dbpass-.

mysql_select_db 1 Selects the database to be associated with the database handle *lin$ identifier- which is the second parameter passed to the function. "n e'ample statement is% /boolval0mys(l)select)db*/dbname /chandle- or die */dbname . ! 3atabase not found.! . /dbuser-.

QUERY Statement 1 The (uery statement is used to send (ueries to the database. The most commonly (ueries are S4L45T 34L4T4 6P3"T4 and #7S48T. #n my code # used mys(l)db)(uery but this statement is depreciated. You should be able to use the statement mys(l)(uery without the database name string. 9ust remember that the (uery will be to the last selected database or last (ueried database. "n e'ample statement is% /result 0 mys(l)db)(uery*/dbname /(uery:- or die*!;ailed Query of ! . /(uery:-. This statement relies on the (uery statement provided above as !/(uery:!. There are several types of (ueries which can be performed using mys(l)db)(uery or mys(l)(uery. Some of the commonly used ones are.
o

Select 1 6sed to get information from the database. This statement will return the contents of all matching database entries. /(uery:0!select < from ! . /mainsection . ! as t: where t:.idname 0 ! . !=!! . /section> . !=!

The variable !/mainsection! is the name of the table the delete operation will be performed on. The item t: is used to identify the database fields and idname is the name of one of the fields. The variable !/section>! is a string that the value in the idname field is to match in order to (ualify the database entry for retrieval into the result value when the (uery call is done. ?hen inside (uotes *!...!- use of =! is used to place a (uote in a (uery statement which is how this is used in the above statement.
o

Delete 1 6sed to remove a database entry. "n e'ample (uery statement using delete is% /(uery:0!delete from ! . /mainsection . ! where id 0 ! . /value. The variable !/mainsection! is the name of the table the delete operation will be performed on. The id is a database field used as a uni(ue identifier.

Update 1 6sed to change the value of a field one or more database entries. "n e'ample (uery statement using update is% /newval 0 :. /(uery:0!update ! . /mainsection . ! set dbflag0! . /newval . ! where id 0 ! . /value. The variable !/mainsection! is the name of the table the delete operation will be performed on. The dbflag is a database field which is being set to a value of :.

nsert 1 6sed to add a new database entry to the database. "ny field value not specified here will be set to the default value for the field. "n e'ample (uery statement using insert is% /(uery:0!insert into ! . /mainsection . ! *url sitetitle description gifurl cat: email creator id entdate sitetype- values *=!! . /url . !=! =!! . /title . !=! =!! . /description . !=! =!! . /gifurl . !=! =!! . /category . !=! =!! . /email . !=! =!! . /uname . !=! ! . /i> . ! 5683"T4*- ! . /stype . !-!.

mysql_!etc"_ro# 1 6sed to get the results of a (uery row by row. "n e'ample is /thisrow0mys(l)fetch)row*/result-

The above statement will only return one row or returned database entry. The value returned is an array of field values in the database. The e'ample below will read all the returned rows and print the field names and values out.
while($thisrow=mysql_fetch_row($result)) { $i=0; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo $field_name . "=" . $thisrow $i! . "<"r#"; $i$$; % %

@ mysql_close 1 6sed to close the database. "n e'ample% mys(l)close*/chandle-.

PHP MYSQL E'ample


Relow is an e'ample of how to use the mys(l functions supported by PHP to access a MySQL database. Here is the file !dblist.php!.
<)*h* session_start(); )# <1234.567 8.9: 6;+:<4 "=>>?@4>>2.2 8.9: A.0& .ransitional>>7B"# <html# <head# <meta htt*=equi-="4ontent=.y*e" content="teCt>html; charset=iso=DD0E=&"# <meta name="descri*tion" content="2ata"ase :ist"# <title#2ata"ase :ist<>title# <>head# <"ody# <)*h* if ($location&=="data"ase") { $chandle = mysql_*connect("localhost", $username, $*assword) or die("4onnection Kailure to 2ata"ase");

session_reHister("data"ase"); $data"ase=$L;7,5_S.,<BF; >> .he data"ase name is *assed usinH L;7,5_S.,<BF mysql_select_d"($data"ase, $chandle) or die ("2ata"ase not found."); $ta"lelist=mysql_list_ta"les($data"ase); echo "<8@#G-aila"le .a"les in the ", $data"ase, " 2ata"ase/<>8@#"; echo "<;:#"; $ta"le = 0; while ($ta"le < mysql_num_rows($ta"lelist)) { $ta"lename=mysql_ta"lename($ta"lelist, $ta"le); echo "<:<#<G href=O"d"list.*h*)", $ta"lename, "O"#", $ta"lename, "<>G#<+,#"; $ta"le$$; % echo "<>;:#"; mysql_close($chandle); $location&="ta"le"; % elseif ($location&=="ta"le") { $chandle = mysql_*connect("localhost", $username, $*assword) or die("4onnection Kailure to 2ata"ase"); mysql_select_d"($data"ase, $chandle) or die ("2ata"ase not found."); $query&="select J from " . $L;7,5_S.,<BF; $result = mysql_d"_query($data"ase, $query&) or die("Kailed Luery"); $i=0; echo "<ta"le rules=O"allO"#<tr#"; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo "<th#", $field_name=#name, "<>th#"; $i$$; % echo "<>tr#"; while ($thisrow=mysql_fetch_row($result)) >>Het one row at a time { echo "<tr#"; $i=0; while ($i < mysql_num_fields($result)) >>*rint all items in the row { echo $thisrow $i!, "<"r#"; $i$$; % echo "<>tr#"; % echo "<>ta"le#"; mysql_free_result($result); mysql_close($chandle);

% )# <>"ody# <>html#

The value of location: is initialiLed in the file in section N called !6sing PHP with ;orms!. #t is passed using sessions and is used to tell if we are showing the available databases or tables. #ts value is initally !database! then it is changed to !table!. #n this e'ample one feature is that two strings are added using the period sign. HereSs the line that adds the strings% /(uery:0!select < from ! . /Q648Y)ST8#7F. Mys(l functions that are used include%

/chandle 0 mys(l)pconnect*!localhost! /username /password- 1 6sed to connect to the server. mys(l)select)db*/database /chandle- 1 6sed to select the default database to (uery. /tablelist0mys(l)list)tables*/database- 1 6sed to get a list of tables that are available in the database. This list is a dimensioned string and the following two functions are used to list the names of the tables% o mys(l)num)rows*/tablelist- 1 #ndicates the number of items in the tablelist string. o /tablename0mys(l)tablename*/tablelist /table-. 1 This is used to get the name of the table from the string of availabel tables using the table list reference and the inde' value. /result 0 mys(l)db)(uery*/database /(uery:- 1 6sed to send a (uery to the database. o mys(l)num)fields*/result- 1 6sed to determine the number of fields in the (uery result. o field)name0mys(l)fetch)field*/result /i-. 1 6sed to get the field obJect *not the name- for the (uery with the specified inde'. o /thisrow0mys(l)fetch)row*/result-. 1 6sed to get the entire row. This is a string array. mys(l)free)result*/result-. 1 ;rees the memory occupied by the /result string. mys(l)close*/chandle-. 1 5loses the connection to the mys(l database server.

"lthough it is functional this file is not nearly complete. #t does not allow for multiple (ueries based on one login. "dditional controls should be added to ma$e this e'ample completely functional.

PHP SQL Connect

This statement opens a connection to the database server. The !mys(l)connect! or !mys(l)pconnect! statements may be used to do this. # recommend that the !mys(l)connect! statement be normally used e'cept for special circumstances. This is because the !mys(l)pconnect! statement is used to establish a permanent connection to the database. The !mys(l)close! statement will 72T end connections opened with the !mys(l)pconnect! statement. #f you use the !mys(l)pconnect! statement to connect to your database on your website you may start getting errors stating that you have too many connections open to the database and additional connections will be refused.

PHP SQL Connect Statement Synta'


The synta' for the mys(l)connect statement is shown below. This statement will open a connection to the server. The !mys(l)select)db! statement must be used later to select the database on the server to be used. resource mys(l)connect * +string server + string username + string password + bool new)lin$ + int client)flags,,,,,-

PHP SQL Connect Statement E'ample


#n this e'ample a connection is made to the database using the user called !username! with a passsword of !password!. You will want to use a uni(ue password. The name !localhost! is used to specify that the database is on the same server that the PHP program is running on. This is your webserver. The handle to the database is returned in the variable !/chandle!. #f the call fails the string contained after the !or die! part of the statement will be e'ecuted and program e'ecution will stop.
$d"user="username"; $d"*ass="*assword"; $d"name="mydata"; >>the name of the data"ase $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); echo "4onnected to data"ase ser-er<"r#"; mysql_select_d"($d"name, $chandle) or die ($d"name . " 2ata"ase not found." . $d"user); echo "2ata"ase " . $data"ase . " is selected"; mysql_close($chandle);

PHP SQL Select Database


PHP SQL Select D. Statement Synta'
The synta' for the mys(l)select)db statement is shown below. This statement will select the database that future (ueries will be sent to. bool mys(l)select)db * string database)name + resource lin$)identifier,-

The value returned is true if there is success and it is false if the command failed.

PHP SQL Select D. Statement E'ample


$d"user="username"; $d"*ass="*assword"; $d"name="mydata"; >>the name of the data"ase $chandle = mysql_connect("localhost", $d"user, $d"*ass) or die("4onnection Kailure to 2ata"ase"); echo "4onnected to data"ase ser-er<"r#"; mysql_select_db($dbname, $chandle) or die ($dbname . " Database not ound." . $dbuser); echo "2ata"ase " . $data"ase . " is selected"; mysql_close($chandle);

PHP SQL Select Q&ery and -ettin, ro#s


The SQL (uery statement is uset to access the database. #t can be used to read the database or write to the database. This page discusses the use of the (uery statement to read the database. The PHP MySQL introduction page e'plains some (uery call types and what they are used forhere.

PHP SQL Q&ery Statement Synta'


There are two (uery statements which may be used they are mys(l)db)(uery and mys(l)(uery. The statement mys(l)db)(uery is depreciated and it is recommend that the mys(l)(uery statement is used. The synta' for both statements is shown below. resource mys(l)db)(uery * string database string (uery + resource lin$)identifier,resource mys(l)(uery * string (uery + resource lin$)identifier,-

PHP SQL Q&ery Statement E'ample


The below e'ample performs a (uery loo$ing for an idname called !Home! in the database table !sections!.
$d"user="username"; $d"*ass="*assword"; $d"name="mydata"; >>the name of the data"ase $chandle = mysql_connect("localhost", $d"user, $d"*ass)

or die("4onnection Kailure to 2ata"ase"); mysql_select_d"($d"name, $chandle) or die ($d"name . " 2ata"ase not found. " . $d"user); $mainsection="sections"; >>.he name of the ta"le $query&="select J from " . $mainsection . " as t& where t&.idname = " . "O"8omeO""; >>select the home section $result = mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); >>do the query $thisrow=mysql_fetch_row($result); if ($thisrow) >>if the results of the query are not null { echo ".he 8ome section was found.<"r#"; % else { echo ".he 8ome section was not found.<"r#"; %

?hen a (uery is done the results can be placed in a specific order. The e'ample below shows how to do this using the order by phrase. ?hen the (uery is done with a !order by! sort the results will be displayed in the order re(uested.
$d"user="username"; $d"*ass="*assword"; $d"name="mydata"; >>the name of the data"ase $chandle = mysql_connect("localhost", $d"user, $d"*ass) or die("4onnection Kailure to 2ata"ase"); mysql_select_d"($d"name, $chandle) or die ($d"name . " 2ata"ase not found. " . $d"user); $mainsection="lin's"; >>.he name of the ta"le where we" lin's are stored $query&="select J from " . $mainsection . " as t& where ((t&.acti-e and t&.a**ro-ed) and (t&.cat& = O"" . $section . "O" or t&.cat( = O"" . $section . "O" or t&.cat@ = O"" . $section . "O")) order "y t&.score 27S4, t&.hits 27S4"; >>select all a**ro-ed lin's that "elonH to the current cateHory $result = mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); >>do the query while($thisrow=mysql_fetch_row($result)) { $i=0; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo $thisrow $i! . " "; >>2is*lay all the fields on one line $i$$; % echo <"r#"; >>*ut a "rea' after each data"ase entry %

PHP SQL Delete Q&ery


The delete (uery is used to delete entries from the database. The below e'ample shows how this is done.
$d"user="username"; $d"*ass="*assword"; $d"name="mydata"; >>the name of the data"ase $chandle = mysql_connect("localhost", $d"user, $d"*ass) or die("4onnection Kailure to 2ata"ase"); mysql_select_d"($d"name, $chandle) or die ($d"name . " 2ata"ase not found. " . $d"user); $mainsection="lin's"; >>.he name of the ta"le where we" lin's are stored $idno=&0; $query&="delete from " . $mainsection . " where id = " . $idno; mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); echo ":in' with <2 " . $idno . " has "een deleted as requested.<"r#"; %

The delete item is chosen by ini(ue id number !/idno! which in this case is set to :O. The table the entry is deleted form is the !lin$s! table which is where internet lin$s are stored.

PHP SQL nsert Q&ery


The insert (uery is used to add entries to the database. "ny field value not specified here will be set to the default value for the field. The below e'ample shows how this is done. #n my e'ample # am creating a web site that is a directory of web lin$s. The database to support this effort includes the following fields%

url 1 The internet address of the web page referenced. sitetitle 1 The title of the web page referneced. description 1 The description of the web page referenced. gifurl 1 The optional internet address of a graphic url to be displayed with the lin$. cat: 1 The category the lin$ belongs in email 1 The email of the lin$ creator. creator 1 The alias of the lin$ creator. id 1 The uni(ue id value of the lin$. entdate 1 The date the lin$ was created. sitetype 1 The type of site this is such as commercial educational or government.

The code below creates a new entry into my database setting values as shown. The values of /ure /title /description /gifurl /category /email. /uname and /stype were created earlier from a form submission. These values are automatically available to the PHP page processing the form input. The 5683"T4*- function generates a date string with a value of the current date. /dbuser0!username!. /dbpass0!password!. /dbname0!mydata!. &&the name of the database /chandle 0 mys(l)connect*!localhost! /dbuser /dbpassor die*!5onnection ;ailure to 3atabase!-. mys(l)select)db*/dbname /chandle- or die */dbname . ! 3atabase not found. ! . /dbuser-. /mainsection0!lin$s!. &&The name of the table where web lin$s are stored /(uery:0!insert into ! . /mainsection . ! *url sitetitle description gifurl cat: email creator id entdate sitetype- values *=!! . /url . !=! =!! . /title . !=! =!! . /description . !=! =!! . /gifurl . !=! =!! . /category . !=! =!! . /email . !=! =!! . /uname . !=! ! . /i> . ! 5683"T4*- ! . /stype . !-!. mys(l)db)(uery*/dbname /(uery:- or die*!;ailed Query of ! . /(uery:-.

PHP SQL Update Q&ery


#n this e'ample a delete flag is cleared associated with a database entry is cleared. /dbuser0!username!. /dbpass0!password!. /dbname0!mydata!. &&the name of the database /chandle 0 mys(l)connect*!localhost! /dbuser /dbpassor die*!5onnection ;ailure to 3atabase!-. mys(l)select)db*/dbname /chandle- or die */dbname . ! 3atabase not found. ! . /dbuser-. /mainsection0!lin$s!. &&The name of the table where web lin$s are stored /deletef0O. /(uery:0!update ! . /mainsection . ! set deletef0! . /deletef . ! where id 0 ! . /delete)lin$+/i:,. mys(l)db)(uery*/dbname /(uery:- or die*!;ailed Query of ! . /(uery:-. echo !Lin$ with #3 ! . /delete)lin$+/i:, . ! has had the delete flag cleared and will not be deleted.CbrE!.

PHP +orm Creation

This page will provide an e'ample form which is partially created from the SQL database. #t mi'es HTML and PHP to perform this function. " 9avaScript routine which is shown on the ne't page is used to validate the form. CDphp echo !Cform name0=!addLin$=! onSubmit0=!return chec$;orm*this-.=! action0=!addurl.php=! method0=!P2ST=!E!. DE Ctable align0!center! border 0!O! cellspacing0!O! cellpadding0!O!E CtrECtdECbE68L% C&bEC&tdECtdECinput type0!te't! name0!url! siLe0!UO!EC&tdEC&trE CtrECtdECbE2ptional F#; 68L% C&bEC&tdECtdECinput type0!te't! name0!gifurl! siLe0!UO!EC&tdEC&trE CtrECtdECbETitle% C&bEC&tdECtdECinput type0!te't! name0!title! siLe0!UO!EC&tdEC&trE CtrECtdECbE3escription% C&bEC&tdECtd rowspan 0 !>!ECte'tarea wrap0!virtual! name0!description! value0!! cols0!PO! rows0!P!EC&te'tareaEC&tdECtrE CtrECtdE*6p to >PP chars-C&tdEC&trE CtrECtdECbEYour 7ame% C&bEC&tdECtdECinput type0!te't! name0!uname! siLe0!UO!EC&tdEC&trE CtrECtdECbEYour 41mail% C&bEC&tdECtdECinput type0!te't! name0!email! siLe0!UO!EC&tdEC&trE CtrECtdECbESite Type% C&bEEC&tdECtdECS4L45T 7"M40!stype! S#V40!:!E C2PT#27 A"L640!O!E5ommercial C2PT#27 A"L640!:!EFovernment C2PT#27 A"L640!>!E4ducational C2PT#27 A"L640!I!EPersonal C2PT#27 A"L640!B!E2rganiLational C&selectE C&tdEC&trE CtrECtdECbE5ategory% C&bEC&tdECtdE CDphp /chandle 0 mys(l)connect*!localhost! /dbuser /dbpassor die*!5onnection ;ailure to 3atabase!-. mys(l)select)db*/dbname /chandle- or die *!3atabase not found.!-. /mainsection0!sections!. /(uery:0!select < from ! . /mainsection . ! order by t:.name!. &&select all sections /result 0 mys(l)db)(uery*/dbname /(uery:- or die*!;ailed Query of ! . /(uery:-. while*/thisrow0mys(l)fetch)row*/result-G /sectdesc+/i:,0/thisrow+:,.

/sectid+/i:,0/thisrow+O,. &&set section values at level :. /i:WW. H DE CS4L45T 7"M40!category! S#V40!:!E CDphp echo !C2PT#27 A"L640=!=!E !. for */i>0:. /i>C0/i:. /i>WWG echo !C2PT#27 A"L640=!! . /sectid+/i>, . !=!E! . /sectdesc+/i>,. H DE C&selectEC&tdECtrE C&tableE Ctable align0!center! border 0!O! cellspacing0!P! cellpadding0!P!E CtrECtdECinput type0!submit! name0!submit! value0!"dd&5hange Lin$!EC&tdECtdECinput type0!reset! value0!5lear ;orm!EC&tdECtrE C&tableE C&formE The available categories are built from the PHP database by reading the available sections and setting their order to be alphabetical.

PHP +orm *alidation


#n the PHP form creation page the following line was used to start the form. Cform name0!addLin$! onSubmit0!return chec$;orm*this-.! action0!addurl.php! method0!P2ST!E This line invo$es a 9avaScript routine which is contained in the HTML header part of the page. #f this routine returns with a successful status the action item is called which means that !addurl.php! is called and data from the form is passed to it. Sessions are not re(uired to pass this data to the addurl.php file and the names of values created on the form page will be available. These values include%

title description uname email stype category

This 9avaScript function will chec$ to be sure there is a 68L title lin$ description and category entered.
<S4,<6. :GBF;GF7="Ya-aScri*t"# <1== function chec'Korm(.heKorm) { >> url, title, descri*tion if (.heKorm.url.-alue.lenHth == 0) { .heKorm.url.-alue = *rom*t("5ou forHot to enter the lin' ;,: for addition1"); return false; % if (.heKorm.title.-alue.lenHth == 0) { .heKorm.title.-alue = *rom*t("5ou forHot to enter the lin' title for addition1"); return false; % if (.heKorm.descri*tion.-alue.lenHth == 0) { .heKorm.descri*tion.-alue = *rom*t("5ou forHot to enter the lin' descri*tion for addition1"); return false; % if (.heKorm.cateHory.-alue.lenHth == 0) { .heKorm.cateHory.-alue = alert("5ou forHot to enter the cateHory1"); return false; % return true; %>> end function chec'alKorm >> ==# <>S4,<6.# Kunction -alue=" . $function& . ""; echo "

!ou "ubmitted#
"; else >>add ;,: { $mainsection="lin's"; $query&="select J from " . $mainsection . " order "y id"; $result = mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); $i&=&; $i(=0; while($thisrow=mysql_fetch_row($result)) >>Het one row { if ($i&<$thisrow $idn!) { if ($i(==0) $i(=$i&; % $i&$$; %

if ($i(==0) $i(=$i&; >>$i( is now the lowest -alue for id. $i&=0; >> Search for the current url $query(="select J from " . $mainsection . " as t& where t&.url = O"" . $url . "O""; >>:oo' for the lin' in the current system =&A0 $result = mysql_d"_query($d"name, $query() or die("Kailed Luery of " . $query(); if ($thisrow=mysql_fetch_row($result)) >> <f already in system { if (($cateHory==$thisrow $cat&n!) or ($cateHory==$thisrow $cat(n!) or ($cateHory==$thisrow $cat@n!) or ($cateHory==$thisrow $catAn!)) >>in requested cateHory { echo " .he ;,: is already listed in the requested cateHory. "; echo ";,: name/ " . $url . " "; if ($thisrow $a**ro-!==0) echo "6lease "e *atient, it is not yet a**ro-ed for main -iewinH. "; if ($thisrow $acti-en!==0) echo "<t is shown as inacti-e, *lease send us an e=mail if it is acti-e. "; echo ".han' you for your interest. ";

% else >>not in the requested cateHory { echo "

>>A(&

.he ;,: is already listed in another cateHory. "; echo ";,: name/ " . $url . " "; if ($thisrow $a**ro-!==0) echo "6lease "e *atient, it is not yet a**ro-ed for main -iewinH. "; if ($thisrow $acti-en!==0) echo "<t is shown as inacti-e, *lease send us an e=mail if it is acti-e.

"; echo ".han' you for your interest. "; % % else >>not in system { $i&=&; $id=$i(; >> $query&="insert into " . $mainsection . " (url, sitetitle, descri*tion, Hifurl, cat&, email, creator, id, entdate, sitety*e) -alues (O"" . $url . "O",O"" . $title . "O",O"" . $descri*tion . "O",O"" . $Hifurl . "O",O"" . $cateHory . "O",O"" . $email . "O",O"" . $uname . "O"," . $i( . ", 4;,2G.7())"; >>&M@ $query&="insert into " . $mainsection . " (url, sitetitle, descri*tion, Hifurl, cat&, email, creator, id, entdate, sitety*e) -alues (O"" . $url . "O",O"" . $title . "O",O"" . $descri*tion . "O",O"" . $Hifurl . "O",O"" . $cateHory . "O",O"" . $email . "O",O"" . $uname . "O"," . $i( . ", 4;,2G.7()," . $sty*e . ")"; >>&M@ mysql_d"_query($d"name, $query&) or die("Kailed Luery of " . $query&); echo "$%&# " . $url . " "; echo "'itle# " . $title . " "; echo "Description# " . $description . " "; echo "(i $%&# " . $)i url . " "; echo "$ser *ame# " . $uname . " "; echo "+,mail address# " . $email . " "; echo ".he chanHes will "e final when they are a**ro-ed "y our staff. "; % >>@DE % >>end add ;,:

Das könnte Ihnen auch gefallen