Ip-Ch 4
Ip-Ch 4
Ip-Ch 4
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.
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
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
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’)”;
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.
$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
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
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])