Ip-Ch 4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

Chapter 4

Connecting with Database

Tell your self, I can do any thing!!


3.1 Database Programming
 PHP is particularly strong in its ability to interact with databases.
 PHP supports pretty much every database out there
 The most commonly used database with PHP is MySQL

 MySQL is a free and open source database that has a lot of users
especially for web applications.
 The steps to interact with a database:
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.1 Database Programming…
Connecting to the database
 The first step in a database interaction is connecting to the database.

 You use a PHP function to connect to the database.

 To make the connection, you need to supply the function with three
things:
 Location:
 The database may not be on the same computer where PHP is
installed.
 Therefore, you need to tell the PHP connect function the name of the
computer where the database is located.
 You can supply either a domain name (such as mycompany.com) or
an IP address (such as 172.17.204.2).
 If the database is on the same computer as PHP, you can use localhost
for the hostname.
Cont.
 Account name: You must provide a valid account
name that can be used to access the database.
 Password: You have to have a valid password to
access the database.
3.1 Database Programming…
Creating database in MySQL using WAMP…
 Creating database

 Creating a table in a database:

 Enter table name and number of columns

 Enter name, data-type and other required

properties for columns


 Click create table button
3.1 Database Programming…
 Created table and value
ID FirstName LastName Sex Telephone Status
sam232 John Walter M 4325456342 1
sam543 Samuel David M 5424256345 1
sam534 George Graham M 2634345643 0
sam979 Ana Bush F 3462737485 0

Sample database table used as an example


3.1 Database Programming…
 Connecting PHP with MySQL
 The syntax for creating connection to MySQL

database:
$connect = mysql_connect($host, $account,
$password);
 mysql_connect(“hostname” ,”username”,
”password”)
 mysql_connect(“localhost”,”root”,””)
 If there is an error – mysql_error() returns error
string from last MySQL call
Connect with
Empty password Error
server
Host name message
username

Select database Database name


3.1 Database Programming…
 After connecting to the database, the next step is
selecting database.
 An RDBMS can create and maintain many databases, so
you need to tell it which database you want to use.

 The syntax for selecting database is:


$db = mysql_select_db(string database, [int
database_connection] );
 mysql_select_db(“database name”)
 mysql_select_db(“testdatabase”)
3.1 Database Programming…
Querying the Database
 To actually perform the query, we can use the mysql_query() function.

 Before doing this, however, it’s a good idea to set up the query you want to

run:
$query = “select * from books“;
$query = “insert into book(Title,Author,Price) value (‘Fikir Eskemekabir’ ,
‘Adiss Alemayehu’, ‘190’)”;

 We can now run the query:


$result = mysql_query($query);

 The mysql_query() function has the following prototype:


mysql_query(string query, [int dbconnection] );

 You pass it the query you want to run, and optionally, the database
connection created.
3.1 Database Programming…
 Example: executing query
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
 Putting all together:
<?php
$account = “david”;
$password = “gotago”;
$host= “localhost”;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(“Catalog”, $connect);
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
//other code
?>
3.1 Database Programming…
Processing Data
 To process the data returned from database, you need to get it

from the temporary table where it is placed when the SQL query
is executed.
 We use PHP database functions to get the data from the

temporary table.

 The data is stored in the temporary table in rows and columns.


 You can use PHP functions to retrieve one row from the table and
store it in an array
 The array has the field names as the array keys.
 For MySQL, the statement is as follows:
$row = mysql_fetch_array($result);
3.1 Database Programming…
 It requires one of the mysql_fetch functions to make the
data fully available to PHP.
 The fetching functions of PHP are as follows:
 mysql_fetch_array: returns rows as associative or numbered
array
 mysql_fetch_assoc: returns rows as associative array
 mysql_fetch_row: returns row as an enumerated array
 mysql_fetch_object: returns row as an object
 mysql_result: returns one cell of data
 The difference between the three main fetching functions
is small.
3.1 Database Programming…
 The most useful fetching function, mysql_fetch_array, offers the
choice of results as an associative or an enumerated array or both
 The default is returning as both (index or key).
 This means you can refer to outputs by database field name rather
than number:
$query = “SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
3.1 Database Programming…
 An important thing to note is that using mysql_fetch_array() is not
significantly slower than using mysql_fetch_row(),. while it
provides a significant added value.
 mysql_fetch_array can also be used with numerical identifiers
rather than field names.
 If you want to specify index or field name rather than making both
available, you can do it like this:
$offset_row = mysql_fetch_array($result, MYSQL_NUM);
$associative_row = mysql_fetch_array($result, MYSQL_ASSOC);

 It’s also possible to use MYSQL_BOTH as the second value.


$both = mysql_fetch_array($result, MYSQL_BOTH);
3.1 Database Programming…

 The mysql_fetch_assoc function returns an associative array that


corresponds to the fetched row.

 mysql_fetch_assoc(): is equivalent to calling mysql_fetch_array() with


MYSQL_ASSOC for the optional second parameter.
 It only returns an associative array.

$query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
3.1 Database Programming…
 The function mysql_fetch_object performs much the same task
 But the row is returned as an object rather than an array.
 Obviously, this is helpful for those among those who utilize the
object-oriented notation:
$query=“SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result))
{
echo $row->ID;
echo $row->FirstName;
echo $row->LastName<BR>\n”;
}
3.1 Database Programming…
 The most general one is mysql_fetch_row, which can
be used something like this:
$query = “SELECT ID, LastName, FirstName FROM Customers”;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result))
{
print(“$name_row[0] $name_row[1] $name_row[2]<BR>\n”);
}
 This code will output the specified rows from the
database, each line containing one row or the
information associated with a unique ID.
Inserting data in database…
 Insert SQL command:
INSERT INTO `table_name`
(list of columns)
VALUES (list of values)
INSERT INTO users
(‘user_Name’,’user_Email’,’user_Password’)
VALUES (‘$name’,’$email’,’$password’)
 mysql_query(query to execute)
Cont.
post

reg_action.php

name

email

password
 Example: a program that retrieves data from database and display in table
<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(“Sales”);
$query = “SELECT * FROM Customers”;
$result = mysql_query($query);
echo(“<TABLE border=’1’>”);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo('<TD> '.$row["ID"].' </TD> ');
echo('<TD>'. $row["firstname"] . '</TD> ');
echo('<TD> '.$row["lastname"] .'</TD> ');
echo('<TD> '.$row["sex"].' </TD> ');
echo "</tr>";
}
echo(“</TABLE><BR>\n”);
?>
3.1 Database Programming…
Inserting Data into Database
 Inserting new items into the database is remarkably

similar to getting items out of the database.


 You follow the same basic steps

 make a connection,
 send a query, and
 check the results.
 In this case, the query you send will be an INSERT
rather than a SELECT.
3.1 Database Programming…
 Simple form with five fields and one button
3.1 Database Programming…
<HTML>
<HEAD>
<TITLE>Processing HTML forms with PHP</TITLE>
</HEAD>
<BODY>
<H1>Newsletter sign-up form</H1>
<P> Please, fill the form to be our registered customer</P>
<FORM METHOD=”post” ACTION=”customer.php”>
ID: <INPUT TYPE=”text” NAME=”ID”> <BR>
First name: <INPUT TYPE=”text” NAME=”FirstName”> <BR>
Last name: <INPUT TYPE=”text” NAME=”LastName”> <BR>
Sex: <INPUT TYPE=”text” NAME=”Sex”> <BR>
Telephone: <INPUT TYPE=”text” NAME=”Telephone”> <BR><BR>
<INPUT TYPE=”submit” NAME=”submit” VALUE=”Submit”>
</FORM>
</BODY>
The customer.php file that process the data collected by the above form is the following:
<?php
// Open connection to the database
$con = mysql_connect(“localhost”, “phpuser”, “sesame”) or
die(“Failure to connect to database”);
mysql_select_db(“customers”);

$ID = $_POST[“ID”]);
$fn = $_POST[“FirstName”];
$ln = $_POST[“LastName”];
$sx = $_POST[“Sex”];
$tl = $_POST[“Telephone”];
$st = “1”;

$query = “INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st)”;
$result = mysql_query($query);
if (mysql_affected_rows($result) >= 1)
echo ‘<P>Your information has been saved.</P>’;
else
echo ‘<P>Something went wrong with your signup attempt.</P>’;
?>
3.1 Database Programming…
 In addition to insertion, you can do many other operations on database using SQL
 SELECT item_list FROM table_list WHERE search_condition;
select lname, fname, balance from account where balance > 10000
 CREATE TABLE table-name (column-name data-type, .... )
Create table customer(lname varchar(20), fname varchar(20), branch varchar(30), balance
number);
 INSERT INTO table_name(column_names) VALUES (value_list)
INSERT INTO account (lname, fname, branch, balance) VALUES ('john', 'smith', 101,
10000)
 DELETE FROM table_name WHERE search_condition
DELETE FROM account where fname = 'john' and lname = 'smith'
 UPDATE table_name SET column_names expression WHERE condition
UPDATE account SET balance = balance * 1.06 where balance > 1000
3.1 Database Programming…
Closing the connection
 Any open database connections are closed when the script
ends.
 However, it is good programming practice to close the
connections in the script to avoid any possible problems.
 You close database connections with a PHP function
 For example, for MySQL, use the following function to close
a database connection:
mysql_close($connect);
Other PHP-Database Functions
 mysql_affected_rows () — Get number of affected rows in previous
MySQL operation.
 It helps you to know how many rows have been deleted, inserted,
modified, etc. by the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])

 mysql_affected_rows() returns the number of rows affected by the last


INSERT, UPDATE or DELETE query associated with link_identifier.

 mysql_create_db () — Create a MySQL database. The syntax is:


bool mysql_create_db (string databasename [, resource link_identifier]);
 mysql_create_db() attempts to create a new database on the server
associated with the specified link identifier.
Other PHP-Database
Functions…
 mysql_drop_db — Drop (delete) a MySQL database
 mysql_drop_db() attempts to drop (remove) an entire database from the
server associated with the specified link identifier.
bool mysql_drop_db (string database_name [, resource link_identifier])

 mysql_num_rows — Get number of rows in result.


 The syntax is:
int mysql_num_rows (resource result);
 mysql_num_rows() returns the number of rows in a result set.
 This command is only valid for SELECT statements.
 To get rows affected by INSERT, UPDATE or DELETE query, use
mysql_affected_rows().

 mysql_num_fields — Get number of fields in result. The syntax is:


int mysql_num_fields (resource result);
Other PHP-Database
Functions…
 mysql_field_name — Get the name of the specified field in a result.
string mysql_field_name (resource result, int field_index)
 mysql_field_name() returns the name of the specified field index.
 field_index is the numerical offset of the field.
 Note that field_index starts at 0.

 mysql_list_tables — List tables in a MySQL database.


resource mysql_list_tables (string database [, resource link_identifier])
 mysql_list_tables() takes a database name and returns a result pointer much
like the mysql_query() function.
 You can use the mysql_tablename() function to extract the actual table names
from the result pointer, or any other result table function such as
mysql_fetch_assoc().
Other PHP-Database
Functions…
<?php
$link = mysql_connect('localhost', 'root', 'vertrigo');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_row($db_list)) {
echo $row[0] . "<br>";
}

$tn = mysql_list_tables(“lab", $link);


while($row = mysql_fetch_array($tn, MYSQL_NUM))
{
echo $row[0]."<br>";
}
?>
End !!

You might also like