23
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING, PART-2 Chapter 19of Text Book DATABSE Connection to MySQL / PHP Internet & World Wide Web How to Program, 5/e

© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

Embed Size (px)

Citation preview

Page 1: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

YANBU UNIVERSITY COLLEGEManagement Science Department

© Yanbu University College

Module 6:WEB SERVER AND SERVER SIDE SCRPTING, PART-2

Chapter 19of Text BookDATABSE Connection to MySQL / PHP

Internet & World Wide Web How to Program, 5/e

Page 2: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

DATABASE CONNECTIVITYPHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)PHP Connect to the MySQL ServerUse the PHP mysqli_connect() function to open a new connection to the MySQL server.Open a Connection to the MySQL ServerBefore we can access data in a database, we must open a connection to the MySQL server.In PHP, this is done with the mysqli_connect() function.Syntaxmysqli_connect(host , username , password , dbname);STEPS1. CREATE A USER in PHPMyAdmin2. CREATE A DATABASE3. CONNECT TO DATABASE4. DATA RETREIVAL/ MANIPULATION

Page 3: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Page 4: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Page 5: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Page 6: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Page 7: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP Create Database and TablesA database holds one or more tables.Create a DatabaseThe CREATE DATABASE statement is used to create a database table in MySQL.We must add the CREATE DATABASE statement to the mysqli_query() function to execute the command.The following example creates a database named “MIS352":<?php$con=mysqli_connect(“localhost",“haseena",“husna");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }// Create database$sql="CREATE DATABASE MIS352";if (mysqli_query($con,$sql)) { echo "Database MIS352 created successfully"; }else { echo "Error creating database: " . mysqli_error(); }?>

Page 8: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Create a Table• The CREATE TABLE statement is used to create a table in MySQL.• We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.• The following example creates a table named “MArks", with three columns. The column names will be “STD_ID",

“STD_NAME" and “STD_MARKS":• <?php• $con=mysqli_connect("localhost","PHPClass","hello","MIS352");• // Check connection• if(mysqli_connect_errno())• {• echo "Failed to connect to MySQL:" . mysqli_connect_error();• }• // Create table• $sql="CREATE TABLE Marks(STD_ID CHAR(30),STD_NAME CHAR(30),STD_MARKS INTO(20))";• // Execute query• if(mysqli_query($con,$sql))• {echo "Table Marks created successfully";}• else• { echo "Error in creating table: " . mysqli_error();• }• ?> • Note: When you create a database field of type CHAR, you must specify the maximum length of the field, e.g.

CHAR(50).• The data type specifies what type of data the column can hold.

Page 9: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Insert Into

• Insert Data Into a Database Table• The INSERT INTO statement is used to add new records to a database

table.• Syntax• It is possible to write the INSERT INTO statement in two forms.

• The first form doesn't specify the column names where the data will be inserted, only their values:

• INSERT INTO table_name VALUES (value1, value2, value3,...)• The second form specifies both the column names and the values to

be inserted:• INSERT INTO table_name (column1, column2, column3,...)

VALUES (value1, value2, value3,...)

Page 10: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Insert Into• Example:In the previous slide we created a table named “Marks", with three columns; “STD_ID", “STD_Name" and

“STD_Marks". We will use the same table in this example. The following example adds two new records to the “Marks" table:

• <?php• // connect with the database and user in Php Myadmin• $n=mysqli_connect("localhost","PHPClass","hello","MIS352");• if (mysqli_connect_errno())• {• echo(" Error In connection");• }• else• { echo("database connected");• }• $stuid=($_POST['sid']);• $stuname=($_POST['sn']);• $stumarks=intval($_POST['sa']);• $sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS) values • ('$stuid','$stuname',$stumarks)";• if(mysqli_query($n,$sql))• {echo "<center><h1 style='color:aqua'>Record added successfully";}• else• {echo"error in insertion";}• mysqli_close($n);• ?>

Page 11: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Insert Data From a Form Into a Database

HTML FILE<html><body><h1> Insert your Detail in the DATABSE </h1><FORM ACTION="new_insert.php" method="post"

name="f1"><label>ID &nbsp; &nbsp;<input type="text"

name="sid"></label><br> <br><label>NAME&nbsp; &nbsp;<input type="text"

name="sn"></label><br> <br><label>MARKS&nbsp; &nbsp;<input type="text"

name="sa"></label><br> <br><label><br><br><input type="submit" name="b1" Value="INSERT">

<input type="reset" ></form></body></html>

OUT PUT

Now we will create an HTML form that can be used to add new records to the “MIS352" table. Here is the HTML form:

Page 12: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Insert Data From a Form Into a Database

Inserting record• When a user clicks the submit button in the HTML form in the

example above, the form data is sent to "insert.php".• The "insert.php" file connects to a database, and retrieves the

values from the form with the PHP $_POST variables.• Then, the mysqli_query() function executes the INSERT INTO

statement, and a new record will be added to the “Marks" table.• Here is the "insert.php" page:

Page 13: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Insert Data From a Form Into a Database(contd)

Insert.php<?php// connect with the database and user in Php Myadmin$n=mysqli_connect("localhost","PHPClass","hello","MIS352");if (mysqli_connect_errno()){ echo(" Error In connection"); }else{ echo("database connected"); }$stuid=($_POST['sid']);$stuname=($_POST['sn']);$stumarks=intval($_POST['sa']);$sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS) values ('$stuid','$stuname',$stumarks)";if(mysqli_query($n,$sql)){echo "<center><h1 style='color:aqua'>Record added successfully";}else{echo"error in insertion";}mysqli_close($n);?>

OUTPUT:

Page 14: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Select

• Select Data From a Database Table• The SELECT statement is used to select data from a database.• Syntax• SELECT column_name(s) FROM table_name• To get PHP to execute the statement above we must use the mysqli_query()

function. This function is used to send a query or command to a MySQL connection.

• The example below stores the data returned by the mysql_query() function in the $result variable.

• Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array.

• Each call to mysqli_fetch_array() returns the next row in the recordset.• The while loop loops through all the records in the recordset. To print the

value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).

Page 15: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

<?phpecho "<h1 style='color:magenta'>The contents of Marks Table:</h1><br> <br>";$con=mysqli_connect("localhost","PHPClass","hello","MIS352");// Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }$result = mysqli_query($con,"SELECT * FROM Marks");echo "<center> <table border='1'><tr><th>STD_ID</th><th>STD_NAME</th><th>STD_MARKS</th></tr>";while($row = mysqli_fetch_array($result)) {echo "<tr>";echo "<td>" . $row['STD_ID'] . "</td>";echo "<td>" . $row['STD_NAME'] . "</td>";echo "<td>" . $row['STD_MARKS'] . "</td>";echo "</tr>"; }echo "</center></table>";mysqli_close($con);?>

DATABASE CONNECTIVITY Complete example WITH mysqli_connect()

Page 16: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

<html><Head></head><body><p> ID NAME EMAIL </p><br><?php//connection to the database$con=mysqli_connect("localhost",”haseena",”husna","mis352"); // Check connectionif (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }//execute the SQL query and return records$result = mysqli_query($con,"SELECT * FROM student");//fetch tha data from the databasewhile($row = mysqli_fetch_array($result)) {//display the results echo $row['ID'] . " " . $row['NAME']. " " . $row['EMAIL']; echo "<br />"; }//close the connectionmysqli_close($con);?> </body></html>

DATABASE CONNECTIVITY Complete example WITH mysqli_connect()

Page 17: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Output

Page 18: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

Die() Function

Definition and Usage• The die() function prints a message and exits the

current script.• This function is an alias of the exit() function.• E.g.//connection to the database$dbhandle = mysql_connect(‘hostname’, ‘username’, ‘password’)  or die("Unable to connect to MySQL");

Page 19: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

DATABASE CONNECTIVITY WITH mysql_connect()

• <?php

//connection to the database$dbhandle = mysql_connect(‘hostname’, ‘username’, ‘password’)  or die("Unable to connect to MySQL");

• echo "Connected to MySQL<br>";

//select a database to work with$selected = mysql_select_db("examples",$dbhandle)   or die("Could not select examples");

//execute the SQL query and return records$result = mysql_query("SELECT id, model,year FROM cars");

//fetch tha data from the database while ($row = mysql_fetch_array($result)) {   echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ". //display the results   $row{'year'}."<br>";}//close the connectionmysql_close($dbhandle);?>

Page 20: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL The Where Clause

<?php$con=mysqli_connect("localhost",”PHPClass",”hello","mis352");if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}$result = mysqli_query($con,"SELECT * FROM student WHERE NAME='hia' ");while($row = mysqli_fetch_array($result)){echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL'];echo "<br>";}?>

Page 21: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Order By Keyword

The ORDER BY Keyword• The ORDER BY keyword is used to sort the data in a recordset in ascending order by

default.• If you want to sort the records in a descending order, you can use the DESC keyword

<?php$con=mysqli_connect("localhost",”PHPClass",”Hello","mis352");if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}$result = mysqli_query($con,"SELECT * FROM student ORDER BY ID ");while($row = mysqli_fetch_array($result)){echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL'];echo "<br>";}?>

Page 22: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Update

• The UPDATE statement is used to modify data in a table.<?php$con=mysqli_connect("localhost",”PHPClass",”Hello","mis352");if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}$b ="UPDATE student SET ID=36 WHERE NAME=‘Hasi' AND EMAIL=‘[email protected]'";if (mysqli_query($con,$b)){echo("RECORD UPDATED SUCCESFUL ");}?>

Page 23: © Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,

© Yanbu University College

PHP MySQL Delete

The DELETE FROM statement is used to delete records from a database table.<?php$con=mysqli_connect("localhost","PHPClass","hello","MIS352");// Check connectionif (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}$a="DELETE FROM Marks WHERE STD_NAME='Malak'";if (mysqli_query($con,$a)){echo "1 record Deleted";}else{echo "Error in Deletion the record: " . mysqli_error();}mysqli_close($con);?>

• OUTPUT: