INTERNET PROGRAMMING II
CHAPTER : 4
Connecting to Databases
Outlines
Introduction
Connecting to a MySQL Database
Creating Databases
Creating Tables
PHP MySQL Insert Into
Select Data from a Database Table
PHP MySQL Update
PHP MySQL Delete From
Backup MySQL Database using PHP
2
Introduction
PHP includes functionality that allows us to work directly
with different types of databases like MYSQL database.
A database defines a structure for storing information.
In a database, there are tables that contain rows, columns,
and Cells.
A query in database is a question or a request.
With MySQL, we can query a database for specific
information and have a record set returned.
3
Connecting to a MySQL Database
Before you can access and work with data in a database, you
must create a connection to the database.
In PHP, this is done with the mysqli_connect()function.
Syntax:
mysqli_connect(servername,username,password,dbname);
Parameters Description
Servername(Host) Optional. Either a host name or an IP address.
localhost is the default hostname to the mysql name.
Username Optional. The MySQL user name
Password Optional. The password to log in with
Dbname Optional. The default database to be used when
performing queries
4
Cont’d
In the following example we store the connection in a variable ($con) for
later use in the script.
<?php
$con = mysqli_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
else
{
echo " Successfully Connected with Mysql ";
}
?>
NB: The "die" part will be executed if the connection fails:
5
Closing a Connection
The connection will be closed as soon as the script ends.
To close the connection before, use the mysqli_close()
function.
Example:
<?php
$con = mysqli_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// some code
else
{
mysqli_close($con);
echo " Successfully closed ";
}?>
6
Creating Databases
We could create database from server side using command or
mysql interface or we could create using php code.
The following code uses to create database using PHP,
assume the user name and password is root.
<?php
$t = 'localhost';
$r = 'root';
$s = '';
$conn = mysqli_connect($t, $r, $s);
if(!$conn )
{
die('Could not connect: ' . mysqli_error());
}
7
Cont’d
else
{
echo 'Connected successfully'."<br/>";
$sql = 'CREATE DATABASE ab';
$retval = mysqli_query($conn,$sql);
}
if(!$retval )
{
die('Could not create database: ' . mysqli_error());
}
else
{
echo "Database ab created successfully\n";
}
mysqli_close($conn);
?>
NB: We must add the CREATE DATABASE statement to the mysqli_query()
function to execute the command.
8
Cont’d
Example2:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database my_db created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
9 NB:- We can also create the database using mysql interface
Creating Tables
To create a table, use the CREATE TABLE statement with the
mysqli_query() function.
Example:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
10
Cont’d
else{
echo "Error creating database: " . mysql_error();
}
// Create table in my_db database
mysql_select_db("my_db", $con); // database selection
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
mysql_close($con);
?>
NB: A database must be selected with the mysql_select_db() function
before a table can be created.
11
Primary Keys and Auto Increment Fields
A primary key is used to uniquely identify the rows in a
table.
Each primary key value must be unique within the table.
the primary key field cannot be null because the database
engine requires a value to locate the record.
The primary key field is often an ID number, and is often
used with the AUTO_INCREMENT setting.
AUTO_INCREMENT automatically increases the value of
the field by 1 each time a new record is added.
12
Cont’d
Example:
$sql = "CREATE TABLE person(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int)";
mysql_query($sql,$con);
13
PHP MySQL Insert Into
The INSERT INTO statement with mysql_query() function is used to insert
new records into a database table.
Example:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO person (FirstName, LastName,
Age) VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
14
Insert Data from a Form into a Database
Now we will create an HTML form that can be used to add
new records to the "Person" table.
Here is the HTML form:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname"/><br<br>
Lastname: <input type="text" name="lastname" /><br<br>
Age: <input type="text" name="age" /><br<br>
<input type="submit" />
</form>
</body>
</html>
15
Cont’d
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 mysql_query() function executes the INSERT
INTO statement, and a new record will be added to the
database table.
16
Cont’d
Below is the code for "insert.php" page:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_DB", $con);//selecting the database
$sql="INSERT INTO person(firstname, lastname, age)
VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error()); }
echo "1 record added";
mysql_close($con)
?>
17
Select Data from a Database Table
The SELECT statement is used to select data from a
database.
Example:-
<?php
$con = mysql_connect("localhost",“root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con); //selecting database
$result = mysql_query("SELECT * FROM person");//fetching data
while($row = mysql_fetch_array($result)) //return each row as an array
{
echo $row['FirstName'] . " " . $row['LastName'] ." ".$row['Age']." ";//print the value of row
echo "<br />";}
mysql_close($con);
?>
18
Display the Result in an HTML Table
The following example selects the same data as the
example above, but will display the data in an HTML table:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>";
19
Cont’d
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
20
PHP MySQL The Where Clause
To select only data that matches a specific criteria, add a
WHERE clause to the SELECT statement.
Syntax:-
SELECT column FROM table WHERE column operator value;
To get PHP to execute the statement above we must use
the mysql_query() function.
This function is used to send a query or command to a
MySQL connection.
We can use operators with where like =, !=, >, <, >=, <=,
BETWEEN, LIKE.
21
Cont’d
The following example will select all rows from the "Person" table,
where FirstName='Peter':
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person WHERE
FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
22
The ORDER BY Keyword
The ORDER BY keyword is used to sort the data in a recordset.
The following example selects all the data stored in the "Person" table,
and sorts the result by the "Age" column:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person ORDER BY age");
while($row = mysql_fetch_array($result)){
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>
23
Cont’d
Sort Ascending or Descending:
If you use the ORDER BY keyword, the sort-order of the recordset is
ascending by default (1 before 9 and "a" before "p").
Use the DESC keyword to specify a descending sort-order (9 before 1
and "p" before "a"):
SELECT column_name(s) FROM table_name
ORDER BY column_name DESC;
Order by Two Columns
̶ It is possible to order by more than one column.
̶ When ordering by more than one column, the second column is only
used if the values in the first column are identical:
SELECT column_name(s) FROM table_name
ORDER BY column_name1, column_name2;
24
PHP MySQL Update
The UPDATE statement is used to modify data in a database
table.
Syntax:
UPDATE table_name SET column_name = new_value WHERE
column_name = some_value;
To get PHP to execute the statement above we must use the
mysql_query() function.
This function is used to send a query or command to a MySQL
connection.
25
Cont’d
The following example updates some data in the "Person" table:
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$q=mysql_query("UPDATE Person SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
if (!$q)
{
echo "record not updated successfuly";
}
else{
echo "record updated successfuly";
}
mysql_close($con);
26 ?>
PHP MySQL Delete From
The DELETE FROM statement is used to delete records from a
database table.
Syntax:-
DELETE FROM table_name
WHERE column_name = some_value;
To get PHP to execute the statement above we must use the
mysql_query() function.
This function is used to send a query or command to a MySQL
connection.
27
Cont’d
The following example deletes all the records in the "Person"
table where LastName='Griffin':
<?php
$con = mysql_connect("localhost", "root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con); mysql_query("DELETE
FROM Person WHERE LastName='Griffin'");
mysql_close($con);
?>
28
Deleting Table
Drop Table statement uses to drop the table from the database.
The syntax is: - ‘DROP TABLE tableName';
Example: - The following code uses to remove a table called employee.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = ' ';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP TABLE employee';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete table employee: ' . mysql_error());
}
echo "Table deleted successfully\n";
?>
29
Backup MySQL Database using PHP
Backup uses for safety purpose.
There are different ways to take backup of MySQL database.
Using SQL Command through PHP:-
o SQL SELECT command is used to take a backup of any table.
o Use SELECT INTO OUTFILE query for creating table backup.
30
Cont’d
Example: - the following code used to take back up file from person
table to the temp directory.
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn ){
die('Could not connect: '. mysql_error()); }
else {echo "There is successful connection <br/>";}
$table_name = "person";
$backup_file = "F:/mybackup/person.sql";
mysql_select_db('my_db', $conn);
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM
person";
$retval = mysql_query($sql, $conn);
if(!$retval ) {
die('Could not take data backup: ' . mysql_error()); }
Else{
echo "Backedup data successfully\n";}
mysql_close($conn);
31
?>
Cont’d
To restore data which from backed up some time ago, we use
LOAD DATA INFILE:
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn){
die('Could not connect: ' . mysql_error());}
else{echo "successfully connect with db" ."<br/>";}
$table_name = "person";
//$backup_file = "F:/mybackup/person.sql";
mysql_select_db("univ", $conn);
$sql = "LOAD DATA INFILE 'F:/mybackup/person.sql' INTO
TABLE $table_name ";
$retval = mysql_query($sql, $conn);
if(!$retval) {
die('Could not load data : ' . mysql_error()); }
else{
echo "Loaded data successfully\n";}
mysql_close($conn);
?>
32
Cont’d
Using phpMyAdmin user interface.
̶ To backup up MySQL database using phpMyAdmin
̶ click on the "export" link on phpMyAdmin main page.
̶ Choose the database that we wish to backup,
̶ check the appropriate SQL options and
̶ enter the name for the backup file.
33
Questions?
34