26
Web Programming CS433/CS614 Dr Walid M. Aly lec10 22:32 Dr Walid M. Aly 1 Web Programming Lecture 10 PHP

Lecture10 PHP 2 - aast.edu

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

DrWalidM.Aly

1

WebProgramming

Lecture10

PHP

Page 2: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

PurposeofServer-SideScripting

• databaseaccess§ Webpagecanserveasfront-endtoadatabase

Ømakerequestsfrombrowser,ØpassedontoWebserver,Øcallsaprogramtoaccessthedatabase,Øsendstheresultsbacktothebrowser

Page 3: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

ArchitecturesforDatabaseAccess

Page 4: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

ArchitecturesforDatabaseAccess

• PHP&DatabaseAccess– PHPsupportsmorethan15databases– AnAPIforeachspecificdatabasesystem(e.g.MySQL API)

– ConvenientforWebaccesstodatabases,becausePHPisrunontheWebserver

– Mostwebserverssupportsphp&MYSQL

Page 5: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

MySQLi• The MySQLi Extension (MySQL Improved) is a relational

database driver used in the PHP programming language toprovide an interface with MySQL databases.

• MySQLi is an improved version of the older PHP MySQLdriver, offering various benefits.

• The developers of the PHP programming languagerecommend using MySQLi when dealing with MySQL serverversions 4.1.3 and newer (takes advantage of newfunctionality)

5

Page 6: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_connect()

6

Parameter Descriptionservername CanbeeitherahostnameoranIPaddress.Passingthe NULL valueorthe

string"localhost" tothisparameter,thelocalhostisassumedusername TheMySQLusernamepassword Ifnotprovided or NULL,theMySQLserverwillattempttoauthenticatethe

useragainstthoseuserrecordswhichhavenopasswordonly.dbname Ifprovidedwillspecifythedefaultdatabasetobeusedwhenperforming

queries.port Ifprovided ,Specifies theportnumber toattempttoconnecttotheMySQL

server.socket Ifprovided ,Specifies thesocketornamedpipe thatshouldbeused.

Ø Before you can access data in a database, you must create a connection to the database.

Ø this is done with the mysqli_connect() function.ThisfunctionreturnsanobjectwhichrepresentstheconnectiontoaMySQLServer.,orFALSEand diplays awarningonfailure

mysqli_connect(servername,username,password,dbname,port,socket)Syntax

http://php.net/manual/en/function.mysqli-connect.php

Page 7: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

PHPMySQL Connect&disconnecttoaDatabaseØ ToconnectPHPtoadatabase,usemysqil_connect,Ø Terminatetheconnectiontothedatabasewith

mysqli_close

$db=mysqli_connect("localhost","root","");…………………………………………mysqli_close($db);

Page 8: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

ExampleStopexecutingcodeifnotconnectedandshowacertainmessage

$db=mysqli_connect("localhost","root","") ordie (“cannotestablishconnection ”);echo“ConnectedSuccessfullytodatabase”

die()-exit()

Syntax die(message) die(int)

Parameter DescriptionMessage

integer

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Definition and UsageThedie() function exitsthecurrentscriptThisfunction isanaliasofthe exit() function.

void die ( int $status )void die ([ string $status ] )

Page 9: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_connect_errno()function

9Note:The concatenationoperator(.) isusedtoputtwostringvaluestogether

Themysqli_connect_errno() function returnstheerrorcodefromthelastconnectionerror, ifany

mysqli_connect_errno();

Definition and Usage

Syntax

<?php$con=mysqli_connect("localhost","wrong_user","my_password","my_db");//Checkconnectionif(!$con){die("Connection error:".mysqli_connect_errno()(;}?>

Example

Page 10: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_query()

10

Ø After connection,excute sql statments usingmysqli_query.Ø Returns FALSE onfailure.Ø Forsuccessful SELECT,SHOW,DESCRIBE or EXPLAIN queries

mysqli_query()willreturnamysqli_resultobject.Ø Forothersuccessfulqueriesmysqli_query()willreturn TRUE.

Syntaxmysqli_query(connection,query,resultmode);

Parameter Descriptionconnection Alinkidentifier returnedby mysqli_connect() or mysqli_init()query Thequerystring.resultmode Optional:

Eitherthe MYSQLI_USE_RESULT(Usethisifwehavetoretrievelargeamountofdata)MYSQLI_STORE_RESULT(Thisisdefault)

Ref:http://www.w3schools.com/php/func_mysqli_query.asp

Page 11: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

11

Parameter Descriptionconnection Required. Specifies the MySQL connection to use

dbname Required. Specifies the default database to be used

Definition and UsageThe mysqli_select_db() function is used to change the default database for the connection.Syntaxmysqli_select_db(connection,dbname);

mysqli_select_db()

Page 12: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_affected_rows()

12

Parameter Descriptionconnection Required. Specifies the MySQL connection to

use

Definition and UsageThe mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.

Syntaxmysqli_affected_rows(connection);

Page 13: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_error()

13

Parameter Descriptionconnection Required. Specifies the MySQL connection to

use

Definition and UsageReturnsastringwiththeerrordescription. ""ifnoerroroccurred

Syntaxmysqli_error(connection);ParameterRequired.SpecifiestheMySQLconnectiontouse

Page 14: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

Example:createsadatabasecalled"my_db":

14

<?php$con=mysqil_connect("localhost","peter","abc123");

if(!$con){die("Connection error:".mysqli_connect_errno();}

if(mysqli_query($con, "CREATEDATABASEmy_db“)){echo"Databasecreated";}else{echo"Errorcreatingdatabase:".mysqli_error($con);}

mysqli_close($con);?>

Page 15: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

15

<?php$con=mysqil_connect("localhost","peter","abc123");if(!$con){die("Connection error:".mysqli_connect_errno();}//Createdatabaseif(mysqli_query($con,"CREATEDATABASEmy_db") ) {echo"Databasecreated";}else{echo"Errorcreatingdatabase:".mysqli_error($con); }//Createtablemysqli_select_db($con,“my_db");$sql ="CREATETABLEPersons(FirstName varchar(15),LastName varchar(15),Ageint)";//Executequerymysqli_query($con,$sql);mysqli_close($con);?>

Example:Creatingadatabasewithtables

Page 16: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

16

<?php$con=mysqli_connect("localhost","root","");if(!$con){die("Connection error:".mysqli_connect_errno();}mysqli_select_db($con,"aast")ordie(mysqli_error($con));$statment1="insert intocourses(Code,Title,prerequest)values('cs234','AI','CS244')";$flag=mysqli_query($con,$statment1);if($flag){echo"sql statment excuted";}else{die("sql statment NOTexcuted".mysqli_error($con));}

?>

Example:insertingrecordintotable

http://127.0.0.1/insertDemo/insertDemo.php

N.B:ThecodetoconnecttoserveranduseacertaindatabasecanbeinaseparatePHPfileandembeddedusing require

Database: aast

Table:courses

Page 17: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

<?php$con=mysqil_connect("localhost","mysql_user","mysql_pwd");if(!$con){die("Connectionerror:".mysqli_connect_errno();}

mysqli_select_db($con,"mydb");mysqli_query($con,"DELETEFROMmytableWHEREid<5");$rc =mysqli_affected_rows($con);echo"Recordsdeleted:".$rc;

mysqli_close($con);?>

17

Example: usingmysqli_affected_rows();

Page 18: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

18

Dealingwiththeresultmysqli_fetch_array (result,result_type)Ø Thisfunctionreturnsarowfromtherecordset resultedfrommysqli_query()functionØ Therowisreturnedasanarray ofstringsonsuccess,Ø eachcalltothisfunctioncausesapointertomoveontonextrowØ ThefunctionreturnsFALSEonfailureorwhentherearenomorerows,Ø ThearraytypecanbeMYSQL_ASSOC- Associativearray,withkeysequaltocolumnnamesØ MYSQL_NUM- Numericarray

MYSQL_BOTH- Default.Bothassociativeandnumericarray

Column3Column2Column1

CBA

EDCrow1

row2

row3

$sql ="SELECT*fromPersonWHERELastname='Ahmed’";$result=mysqli_query($sql,$con);$data=(mysqli_fetch_array($result));echo$data[0];echo$data[1];echo$data[2];//ABC//echo$data[“column1”];echo$data[“colum2”];echo$data[“column3”];$data=(mysqli_fetch_array($result));echo$data[0];echo$data[1];echo$data[2];//CDE

Page 19: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

19

<?php$con=mysqli_connect("localhost","root","")ordie("cannotestablishconnection");mysqli_select_db($con,"aast") ordie(mysqli_error($con));

$statment1="SELECT*FROMcourses";$result=mysqli_query($con,$statment1);if(!($result)){echo ("Error:".mysqli_error($con));}while($row=mysqli_fetch_array($result)){echo$row["Code"]."-";echo$row["Title"]."-";echo$row["Prerequest"];echo"<br/>";}

?>

Example:Dealingwiththeresult

http://localhost/selectDemo/selectDemo.php

Database: aast

Table:courses

Page 20: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

mysqli_num_rows()function

20

Parameter Descriptiondata Required. Specifies which data pointer to use. The data

pointer is the result from the mysqli_query() function

Definition and UsageThe mysqli_num_rows() function returns the number of rows in a recordset.This function returns FALSE on failure.

Syntaxmysqli_num_rows(data)

<?php$con=mysqli_connect("localhost", "peter","abc123");if(!$con){die('Couldnotconnect:'.mysql_error());}$db_selected =mysqli_select_db($con,"test_db");$sql ="SELECT*FROMperson";$result=mysqli_query($con,$sql);echomysqli_num_rows($result);mysqli_close($con);?>

Example

Page 21: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

<?php$con=mysqli_connect("localhost","root","") ordie("cannotestablishconnection");mysqli_select_db($con,"aast")ordie(mysqli_error($con));

$statment1="SELECT*FROMcourses";$result=mysqli_query($con,$statment1);

$num_rows =mysqli_num_rows($result);for($row_num =0;$row_num <$num_rows;$row_num++){

$row=mysqli_fetch_array($result);print"<p>Resultrownumber" .

($row_num +1)."Code:";

echo($row["Code"]);echo"Title:";echo($row["Title"]);echo"Prerequest :";echo($row["Prerequest"]);echo"</p>";}?>

Example:Dealingwiththeresultusingmysql_num_rows function

http://localhost/selectDemo/selectDemo2.php

Database: aast

Table:courses

Page 22: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

Example:Insertingrecordsusingaform

insertForm.html

<formmethod="post" action="insertForm.php"><tableborder="1"><tr><td>CourseID</td><td><inputtype="text" name="ID"></td></tr><tr><td>CourseTitle</td><td><inputtype="text" name="title"></td></tr><tr><td>Prerequest </td><td><inputtype="text" name="Prerequest"></td></tr><tr><td><inputtype="submit" value="AddCourse"/></td><td><inputtype="reset" /></td></tr></table></form>

http://localhost/Insert_Form/insertForm.html

Page 23: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

<?php$id=$_POST["ID"];$title=$_POST["title"];$prequest=$_POST["Prerequest"];$con=mysqli_connect("localhost","root","") ordie("cannotestablishconnection");mysqli_select_db($con,"aast");$statment1="insertintocourses(Code,Title,Prerequest) values('$id','$title','$prequest')";$flag=mysqli_query($con,$statment1);if($flag){echo"RecordaddedSuccessfully";}else{die("CannotaddRecord".mysqli_error());}

insertForm.php

Page 24: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

24

http://localhost/FormQuery/FormQuery.php

Example:queryingdatabaseusingaform

Database: aast

Table:courses

Page 25: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

25

<formmethod="post" action="FormQuery.php"><p>CourseCode?</p><selectname="Course_Code"><option>CS433</option><option>CS244 </option><option>CC231</option></select><inputtype="submit“ value="CheckPrerequest"/><inputtype="reset“value="ResetForm"/></form>…………………………………………………

FormQuery.php

FormQuery.php

Page 26: Lecture10 PHP 2 - aast.edu

WebProgramming CS433/CS614DrWalidM.Alylec1022:32

26

<?php$con=mysqli_connect("localhost","root","","aast") ordie("cannotestablishconnection");?>

<?phpif(isset($_POST["Course_Code"])){

$courseCode=$_POST['Course_Code'];$query="SELECTPrerequest fromcourseswhereCode='$courseCode' ";

$result=mysqli_query($con,$query);if(!($result)){echo("Error:".mysqli_error($con));

die("Cannotexecute".mysqli_error());}

$row=mysqli_fetch_array($result);$answer=$row["Prerequest"];echo"<p>ThePrerequest for$courseCode is$answer<p>";}

?></html>