0% found this document useful (0 votes)
19 views

PHPChapter (12!13!14) Databases

This document provides an overview of communicating with MySQL databases using PHP. It discusses SQL queries like SELECT, INSERT, UPDATE, and DELETE and how they are used to retrieve, add, modify and remove data from databases. It also explains the basic steps to connect to a database in PHP, send queries, process results, and close the connection. Examples are given for creating databases and tables, inserting data, extracting and displaying results, and updating, deleting records through forms.

Uploaded by

kaunghtet kyaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

PHPChapter (12!13!14) Databases

This document provides an overview of communicating with MySQL databases using PHP. It discusses SQL queries like SELECT, INSERT, UPDATE, and DELETE and how they are used to retrieve, add, modify and remove data from databases. It also explains the basic steps to connect to a database in PHP, send queries, process results, and close the connection. Examples are given for creating databases and tables, inserting data, extracting and displaying results, and updating, deleting records through forms.

Uploaded by

kaunghtet kyaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

CHAPTER 12, 13 & 14

MySQL Database with PHP

Reference: Beginning PHP 5.3 by Matt Doyle


Communicating with your database
 SQL (Structured Query Language), use to communicate with a database.
 SQL queries can instruct the RDBMS to create a database, create tables
in a database, store data, retrieve data, delete data, and perform many
other actions.
 SELECT — Retrieves data from one or more tables
 INSERT — Inserts data into a table
 UPDATE — Updates data in a table
 DELETE — Deletes data from a table
 CREATE — Creates a database, table
 DROP — Wipes out a database or table

2
Using PHP with a database
The steps to interact with a database are:
1. Connect to the database.
2. Send an SQL query that contains instructions for the
database software.
3. If you retrieved data from the database, process the data.
4. Close the connection to the database.

3
PHP and Databases
In order to make use of a data layer, you must have
access to a database.
You should have one through this course.

You will need a username and password.


These too will be provided to you as part of the course.

For the purposes of this and future lecture slides, we


assume that your database is stored on localhost.
It does not have to be, but this is the usual arrangement.

4
Connecting to the Database
To make the connection to MySQL database:
<?
$host=“localhost”;
$user=“root”;
$pass=“”;

$connection=mysql_connect($host,$user,$pass)
Or die (“Couldn’t connect to database”);
?>

5
Possible Errors
Depending on the level of reporting in your browser,
you may or may not get meaningful error messages if
this goes wrong.
However, if you have a problem it is one of the
following:
The host is not correct.
The username does not exist.
The password does not match the username.

Double check each of these in both your PHP and the


server if possible.

6
A Database Connection
 Having made the connection to the server, you must select the
database with which you are going to work.
<?<?php <<
$host=“localhost”;
$user=“root”;
$pass=“”;
$database=“mydb”;
$connection=mysql_connect($host,$user,$pass)
Or die (“Couldn’t connect to database”);
mysql_select_db($database, $connection);
?>
7
Example 1- Creating Database
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE mydb",$con)) {
echo "Database created"; }
else { echo "Error creating database: " . mysql_error();
}
mysql_close($con); dbcreate1.php
8
?>
Example 1 - Creating a Table
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{ die('Could not connect: ' . mysql_error( ));
}
mysql_select_db("mydb", $con);

$query="CREATE TABLE user( FirstName varchar(15),


SurName varchar(15) )";

$ret=mysql_query($query,$con);
tablecreate.php
9
Example 1 - Creating a Table
if($ret) {
echo "<p>Table created!</p>";
}
else {
echo "<p>Something went wrong: ", mysql_error() +
"</p>";
}
mysql_close($con);

?>

10
Example 2-
Creating Database & Table
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE my_db1",$con))
{ echo "Database created";
}
else {
echo "Error creating database: " . mysql_error();
}
11
Example 2-
Creating Database & Table
// Create table
mysql_select_db("my_db1", $con);

$sql = "CREATE TABLE Persons(FirstName varchar(15),


LastName varchar(15), Age int )”;

// Execute query
mysql_query($sql,$con);

mysql_close($con);
?>

12
Example 3- Creating Table
<?php
mysql_select_db("my_db1", $con);
$sql = "CREATE TABLE User
(
UserID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(UserID),
Name varchar(15),
Address varchar(50),
Age int
)";
mysql_query($sql,$con); // Execute query
mysql_close($con);
?>
13
Inserting Data into a Table (1)
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db1", $con);

$query=“INSERT INTO User


(Name, Address) VALUES(‘MaMa’, ’Yangon')";

14
Inserting Data into a Table (1)
$ret=mysql_query($query,$con);

If($ret) {
echo "<p> User Table is inserted!</p>";
}
Else {
echo "<p>Something went wrong: ", mysql_error() +
"</p>";
}
mysql_close($con);

?>
15
Inserting Data into a Table (2)
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{ die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db1", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName,


Age) VALUES ('Peter', 'Griffin',35)", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName,
Age) VALUES (‘Alan', ‘Smith',33)", $con);
mysql_close($con);
16
?>
Insertion using variables
$first=“John”;
$last=“Smith”;
$age=36;

mysql_query("INSERT INTO Persons (FirstName,


LastName, Age) VALUES (\"$first\", \"$last\", $age)”,
$con);

17
Manipulating the Results
 The results come out as an array of associative arrays.

 The keys of each associative array are the fields in the


database.

 The values are the contents of the database corresponding to


those fields for a record.

 Thus, making use of the data we have queried for the database
requires us to provide handling code in PHP.

18
Extracting the Data
PHP gives us a number of helper functions.
If we want how many records that were returned, we use the
mysql_num_rows function.

This is valuable information we will need if we are to


perform operations on each of the records that were
returned.

The function takes the results of a query as a


parameter, and gives an integer in return.

19
Extracting the Data
<?
$host=“localhost”;
$user=“”;
$pass=“”;
$database=“my_db1”;
$connection=mysql_connect($hosts,$user,$pass)or die(“Couldn’t connect to
datbase”);
mysql_select_db($database,$connection);

$query=“select * from Persons”; //retrieving all records


$ret=mysql_query($query,$connection);
$num_result = mysql_num_row($ret);

echo”<p>There were $num_results results returned from the query.</p>”;


20 ?>
Fetching a Row
The results set form the query contains each of the rows,
but it also contains an internal counter of the last row for
which we asked.

mysql_fetch_array can be used to fetch each row in order.

Each call to the function increments the counter by one.


o to perform manipulation or output on each row of
the results one by one.

21
Fetching a Row
echo ”<table width=\”100%\” border=1>”;
echo ”<tr>”; Last Name Age
echo ”<th align=\”left\”>Last Name</th>”; Griffin 35
Smith 33
echo ”<th align=\”left\”>Age</th>”;
echo ”</tr>”;
for ($i=0; $i<$num_results; $i++)
{ $row = mysql_fetch_array($ret);
echo”<tr>”;
echo”<td>”.$row[“LastName”].”</td>”; //field name = key name
echo”<td>”.$row[“Age”].”</td>”;
echo”</tr>”;
}
22
User Interaction Form
<html>
<head>
<title>Database Form</title>
</head>
<body>
<form action=“database_search.php” method=“POST”>
<p>First Name</p>
<input type=“text” name=“firstname”>
<p>Last Name</p>
<input type=“text” name=“lastname”>
<input type=“reset” value=“clear values”>
<input type=“submit” value=“submit”>
</body>
</html>
23
Form Process
$firstname=$_POST[“firstname”];
$lastname=$_POST[“lastname”];

$query=“SELECT * from Persons


WHERE FirstName=\””.$firstname.
“\” OR LastName= \””.$lastname.”\””;

$ret=mysql_query($query,$connection);
$num_results=mysql_num_rows($ret);

24
Retrieving Data
$firstname=$_POST[“firstname”];
$lastname=$_POST[“lastname”];
$firstname=mysql_real_escape_string($firstname);
$lastname=mysql_real_escape_string($lastname);

$query=“SELECT * from Persons WHERE


FirstName=‘$firstname’ OR LastName=‘$lastname’”;

$ret=mysql_query($query,$connection);

25
Updating Records
UPDATE <table_name> SET <field_name>=‘value’
WHERE <condition>

mysql_query("UPDATE Persons SET Age = 36 WHERE


FirstName = 'Peter' AND LastName = 'Griffin’ ",$con);

26
Deleting Records

DELETE FROM <table_name> WHERE <condition>

mysql_query("DELETE FROM Persons WHERE


LastName='Griffin’ ",$con);

27
Thank You!

28

You might also like