SlideShare a Scribd company logo
PHP-MySQL database
applications
PHP-MySQL database applications
Brief review of MySQL
PHP MySQL functions
examples
Brief Review Of MySQL
The MySQL comand line monitor
Creating database tables
Queries
Command Line Client
Read the MySQL documentation
c:mysqlmysqldocsmanual_toc.html

Read MySQL install instructions on CDSupply a
username
Command to enter monitor is
and a
mysql - u xxxx -p

To execute an SQL script use

password
when
prompted

mysql -u xxxx -p < /path/script.sql

GUI client MyCC is better
Creating Database Tables
Create web_db database to hold the tables:
CREATE DATABASE web_db;

To create a table called notes:
USE web_db;
CREATE TABLE notes (...);
insert some rows for testing if necessary

It is easy to write an sql script called
notes.sql and use monitor to execute it
The Basic Queries
CREATE

create databases and tables

SELECT

select table rows based on certain conditions

DELETE

delete one or more rows of a table

INSERT

insert a new row in a table

UPDATE

update rows in a table

ALTER

alter the structure of a table
PHP MySQL Functions
Connecting to a Database
Making a query
Using results of a query
freeing resources
closing the connection
Connecting To A Database
mysql_connect(server, username, password)
connects to a MySQL server through a port
the default is the string "localhost:3306"
username is a string for the user name
password is a string for the password
returns FALSE on failure

Example
$db_link = mysql_connect("localhost:3306",
"test", "123");

there is also the persistent mysql_pconnect
Example From PHP Docs
<?php
$link = mysql_connect("localhost", "mysql_user",
"mysql_password")
or die("Could not connect: " . mysql_error());
print ("Connected successfully");
mysql_close($link);
?>
Selecting A Database
mysql_select_db(name, link)
select a database given by the string name
the link is optional and specifies the open link
value such as $db_link returned by a connect
statement.
if not supplied the last opened link is used.
returns TRUE on success else FALSE

Example
mysql_select_db("web_db");
Example From PHP Docs
<?php
$lnk = mysql_connect('localhost', 'mysql_user',
'mysql_password')
or die ('Not connected : ' . mysql_error());
// make foo the current db
mysql_select_db('foo', $lnk) or die ('Can't use foo
: ' . mysql_error());
?>
Error Reporting (1)
mysql_error(link)
Return an error string or error number
the link is optional
if not supplied the last opened link is used.
Empty string is returned if there is no error.

Example
mysql_error();
Error Reporting (2)
mysql_no(link)
Return the error number
the link is optional
if not supplied the last opened link is used.
0 is returned if there is no error.

Example
mysql_no();
Example From PHP Docs
<?php
mysql_connect("localhost", "mysql_user",
"mysql_password");
mysql_select_db("nonexistentdb");
echo mysql_errno() . ": " . mysql_error(). "n";
mysql_select_db("kossu");
mysql_query("SELECT * FROM nonexistenttable");
echo mysql_errno() . ": " . mysql_error() . "n";
?>
Making A Query (1)
mysql_query(query, link)
make a select query (link is optional)
query is a string for the MySQL query
Don't end the query with a semi-colon
Return value is a resource identifier or FALSE if
the query is SELECT, SHOW or DESCRIBE

Example (select all rows of books table)
$query = "SELECT * FROM books";
$result = mysql_query($query);
Making A Query (2)
INSERT and UPDATE queries
for these queries a resource is not returned
TRUE is returned on sucess
FALSE is returned on failure

Example (describe the books table)
$query = "DESCRIBE books";
$status = mysql_query($query);
Example From PHP Docs
<?php
$result = mysql_query("SELECT my_col FROM my_tbl")
or die("Invalid query: " . mysql_error());
?>
Retrieving Table Information
mysql_list_fields(database, table, link)
For a select query it retrieves information from
given table in given database. link is optional
The returned resource can be used to obtain
properties of the table such as names of the
table columns and field type information

Example
$fields = mysql_list_fields("web_db",
"books");
Number Of Table Columns
mysql_num_fields(result)
return the numbers of columns in a table
result is the resource returned by a call to the
mysql_list_fields function

Example
$fields = mysql_list_fields("web_db", "books");
$num_columns = mysql_num_fields($fields);
Names Of Table Columns
mysql_field_name(result, index)
return the name of the table column whose
position is given by index (0,1,...)
result is the resource returned by a call to
mysql_list_fields

Example: the first column name
$fields = mysql_list_fields("web_db", "books");
$isbn = mysql_field_name($fields, 0);
Example From PHP Docs
<?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
$fields = mysql_list_fields("database1", "table1",
$link);
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {
echo mysql_field_name($fields, $i) . "n";
}
?>
Accessing Table Rows (1)
mysql_fetch_row(result)
each call returns the next row as an indexed
array where result is a resource returned from a
call to mysql_query (FALSE if no more rows)

Example
$query = "SELECT * FROM books";
$result = mysql_query($query);
$row = mysql_fetch_row($result); // row 0
$isbn = $row[0]; // isbn for row 0
Accessing Table Rows (2)
mysql_fetch_assoc(result)
as in mysql_fetch_row but next row is returned
as an associative array

Example
$query = "SELECT * FROM books";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result); // row 0
$isbn = $row['isbn']; // isbn for row 0
Accessing Table Rows (3)
mysql_fetch_array(result)
combines mysql_fetch_row, mysql_fetch_assoc
returns row information as both an associative
array and an indexed array

Example
$query = "SELECT * FROM books";
$result = mysql_query($query);
$row = mysql_fetch_array($result); // row 0
$isbnA = $row[0]; // isbn for row 0
$isbnB = $row['isbn']; // can also get it this way
Accessing table rows (4)
mysql_num_rows(result)
returns number of rows from a select query
result is the resource returned by the select
query

mysql_affected_rows(result)
used after an INSERT, UPDATE, or DELETE query
to return the number of rows affected
result is the resource returned
Other Functions
mysql_real_escape_string(string,link)
returns a string safe to use in mysql_query

In MySQL 4.1 there are mysqli_... functions
which are supposed to be improved.
There are many other MySQL functions that
we will not use.
See PHP function reference for complete list
Freeing Resources
mysql_free_result(result)
free memory associated with the given resource
called result (after a select query).
Not necessary except for large result sets
Done automatically when script exits.

mysql_close(link)
close the database connection associated with
the given link
doesn't do anything for persistent links.
Processing column names
// Get resource for the field names
$fields = mysql_list_fields("web_db", "books");
// Get number of table columns
$num_cols = mysql_num_fields($fields);
// process them using a for loop
for ($i = 0; $i < $num_cols; $i++)
{
$name = mysql_field_name($fields, $i)
// do something here with $name
}
Processing table rows (1)
while ($row = mysql_fetch_array($result)
{
From SELECT
for ($i = 0; $i < count($row); *i++)
query
{
$col_value = $row[$i]'
// Do something with $col_value here
}
// do end of row processing here
}
// do end of table processing here

Here $row is returned as an array so the inner loop is a
for loop
Processing table rows (2)
while ($row = mysql_fetch_assoc($result)
{
From SELECT
foreach($row as $col_value)
query
{
// Do something with $col_value here
}
// do end of row processing here
}
// do end of table processing here

Here $row is returned as an associated array so the
inner loop is a foreach loop. The foreach is easier to
use.
A db_connect Function
This function can be used in scripts to
connect to a database. Put it in a file called
db_connect.php in your include path
<?php function db_connect($db_name)
{ $host_name = "localhost:3306";
$user_name = "xxxxx"; $password = "yyyyy";
$db_link = mysql_connect($host_name,
$user_name, $password)
or die("Could not connect to $host_name");
mysql_select_db($db_name)
or die("Could not select database $db_name");
return $db_link;
} ?>
Books Display Example (1)
First create the following books.sql file
containing a sample database table
CREATE DATABASE IF NOT EXISTS web_db;
USE web_db;
CREATE TABLE books (
isbn
title
author
pub
year
price
);

CHAR(15)
VARCHAR(100)
VARCHAR(100)
VARCHAR(20)
year
DECIMAL(9,2)

PRIMARY KEY NOT NULL,
NOT NULL,
NOT NULL,
NOT NULL,
NOT NULL,
DEFAULT NULL
Books Display Example (2)
books.sql continued (insert some books)
INSERT INTO books VALUES (
'0-672-31784-2',
'PHP and MySQL Web Development',
'Luke Welling, Laura Thomson',
'Sams', 2001, 74.95
);

Insert a few more (see simplebooks.sql)
Books Display Example (3)
Run books.sql through MySQL using the
command
mysql -u xxxxx -p < c:/.../books.sql
Or use the gui client MyCC
here xxxxx is your MySQL username and the -p
option means to prompt for the password
Now write a PHP script called dbase.php that
displays the books in an HTML table
Output
dbase.php (1)
HTML header information
<?php require_once("db_connect.php"); ?>
<html>
<head>
<title>
Displaying the book database table using PHP
</title>
<h1>Displaying thebook database table using PHP</h1>
<?php
dbase.php (2)
Make a database connection
$db_link = db_connect("web_db");

This uses the function defined in the include
file db_connect.php
My include path in php.ini is
include_path=".;c:Apachephpincludes"
current directory
dbase.php (3)
Send a SELECT query for all columns
$query = "SELECT * FROM books";
$result = mysql_query($query)
or die("SQL Query failed");

Obtain table properties
$fields = mysql_list_fields("web_db", "books");
$num_columns = mysql_num_fields($fields)
dbase.php (4)
Display column headings in an HTML table
echo '<table border="1">', "n";
echo "<tr>n";
for ($i = 0; $i < $num_columns; $i++)
{
echo "<th>", mysql_field_name($fields, $i),
"</th>n";
}
echo "</tr>n";
dbase.php (5)
Display the books table in as an HTML table
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>n";
foreach ($row as $col_value)
{
echo "<td>$col_value</td>n";
}
echo "</tr>n";
}
echo "</table>n";
dbase.php (6)
Free resources and close connection
mysql_free_result($result);
mysql_close($db_link);
?>
</body>
</html>

view script dbase.php
http://localhost/users/MYSQL/dbase.php
Calling Script From Button (1)
Give the button a name and a value
<input type="submit" name="choice" value="Display">

When form is submitted the name will exist
if (isset($_REQUEST['choice'])
{
// process the button click here
}
...

Multiple submit buttons should have different
names or same name, different values
Calling Script From Button (2)
Another approach is to use the submit button
label (value) to distinquish choices
$choice = isset($_REQUEST['choice']) ?
$_REQUEST['choice'] : "";
if ($choice == "Display")
{
// process the button click here
} ...

Multiple submit buttons can have the same
name but different labels (values)
Calling Script From Link
A link can be clicked to invoke the script
again or to pass a parameter to it using the
GET method (query string in link)
<?php
$this_url = $_SERVER['PHP_SELF'];
$edit_url = "$this_url?choice=edit&id=$id";
$delete_url = "$this_url?choice=delete&id=$id";
?>
<a href="<?php echo $edit_url?>">[ Edit ]</a>
<a href="<?php echo $delete_url?>">[ Delete ]</a>
Suggestion Box
Users make suggestions through a textarea
in a form and submit them
Suggestion is saved in a MySQL database
table called sbox in database web_db
Suggestions are displayed along with the
time
view script sbox/sbox.php
http://localhost/php/MYSQL/sbox/sbox.php
Suggestion Box Display

initial
display

display
when
submit link
is clicked
sbox.sql
CREATE DATABASE IF NOT EXITS web_db;
USE web_db;
DROP TABLE IF EXISTS sbox;
CREATE TABLE sbox
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
time DATETIME NOT NULL,
suggestion TEXT NOT NULL
);

view script sbox/sbox.sql
Script Logic
IF request for new suggestion THEN
display form to get new suggestion
ELSE
IF form was submitted THEN
insert suggestion into database table
ENDIF
Retrieve suggestions from database table
IF there are suggestions THEN
display them
ELSE
Suggestion table is empty
ENDIF
ENDIF
provide self link to enter a new suggestion
sbox.php (1)
<?php require_once("db_connect.php"); ?>
<html><head><title>Suggestion Box</title></head>
<body><h1>Suggestion Box</h1>
<?php
$self = $_SERVER['PHP_SELF'];
if (isset($_REQUEST['new'])) // link was clicked
{ ?>
<form action="<?php echo $self ?>" method="POST">
Enter your suggestion:<br>
<textarea name="suggestion" rows="5" cols="50"
</textarea><br>
<p><input type="submit" name="add"
value="Submit"></p>
</form>
<?php }
sbox.php (2)
else
{
$db_link = db_connect("web_db");
if (isset($_REQUEST['add']))
{
$suggestion = $_REQUEST['suggestion'];
$query = "INSERT INTO sbox SET time=NOW(),"
. "suggestion='$suggestion'";
mysql_query($query);
}

Forgot to use addslashes and stripslashes
sbox.php (3)
// Display all the suggestions
$query = "SELECT time, suggestion FROM sbox";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$time = $row['time'];
$suggestion = $row['suggestion'];
echo "<b>$time:</b> $suggesion<br>n";
}
}
else
sbox.php (4)
{
echo "The suggestion box is empty";
}
?>
<p><a href="<?php echo $self ?>?new=1">
Submit a new suggestion</a></p>
</body>
</html>
<?php
}
A trick for
?>
calling a
script from a
link with a
view script sbox/sbox.php
parameter
Other Versions
There are versions sbox2, sbox3, sbox4
sbox2 handles quotes and HTML text properly
sbox3 adds error checking
sbox4 is a simpler version of sbox3 for which the
form is always displayed so no link is needed to
add a new suggestion.
sbox4.php (1)
<?php
require_once("db_connect.php");
$db_link = db_connect("web_db");
$self = $_SERVER['PHP_SELF'];
?>
<html><head><title>Suggestion Box</title></head>
<body><h1>Suggestion Box</h1>
<form action="<?php echo $self ?>" method="POST">
Enter your suggestion:<br>
<textarea name="suggestion" rows="5" cols="50"
</textarea><br>
<p><input type="submit" name="add"
value="Submit"></p>
</form>
sbox4.php (2)
<?php
// add a new suggestion if there is one
if (isset($_POST['add']))
{
$suggestion = addslashes($_POST['suggestion']);
if (strlen($suggestion) > 0)
{
$query = "INSERT INTO sbox SET time=NOW(),
suggestion='$suggestion'";
mysql_query($query);
}
}
sbox4.php (3)
// display all the suggestions
$query = "SELECT time, suggestion FROM sbox ORDER
BY time DESC";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$time = $row['time'];
$suggestion = htmlspecialchars(stripslashes(
$row['suggestion']));
echo "<strong>$time:</strong> $suggestion<br>
n";
}
}
sbox4.php (4)
else
{
echo "The suggestion box is empty";
}
?>
</body>
</html>
Ad

More Related Content

What's hot (20)

javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
PHP
PHPPHP
PHP
Steve Fort
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
WordPress Memphis
 
Php forms
Php formsPhp forms
Php forms
Anne Lee
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
Maitree Patel
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
joins in database
 joins in database joins in database
joins in database
Sultan Arshad
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP FormsPHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
Id and class selector
Id and class selectorId and class selector
Id and class selector
MyCredentials YourReference
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
Md. Mahedee Hasan
 
Dhtml ppt (2)
Dhtml ppt (2)Dhtml ppt (2)
Dhtml ppt (2)
Rai Saheb Bhanwar Singh College Nasrullaganj
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
Partnered Health
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
Nisa Soomro
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 

Viewers also liked (13)

Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?
Carl Sack
 
Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundaries
Carl Sack
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can You
Carl Sack
 
PHP code examples
PHP code examplesPHP code examples
PHP code examples
programmingslides
 
Jquery examples
Jquery examplesJquery examples
Jquery examples
programmingslides
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
Zunair Sagitarioux
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Cedric Spillebeen
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
Ishtdeep Hora
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
Ron Reiter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?
Carl Sack
 
Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundaries
Carl Sack
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can You
Carl Sack
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
Zunair Sagitarioux
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Cedric Spillebeen
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
Ron Reiter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Ad

Similar to PHP and Mysql (20)

PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
Firdaus Adib
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
saritasingh19866
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
wahidullah mudaser
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
chapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptxchapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptx
Getawu
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
SEO Training in Chandigarh
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
moirarandell
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
CBitss Technologies
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
CBitss Technologies
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
Priti Solanki
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Php 2
Php 2Php 2
Php 2
tnngo2
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Collection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docxCollection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docx
KingKhaliilHayat
 
Php summary
Php summaryPhp summary
Php summary
Michelle Darling
 
Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
abhikwb
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
Firdaus Adib
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
saritasingh19866
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
chapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptxchapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptx
Getawu
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
moirarandell
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
Priti Solanki
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Collection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docxCollection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docx
KingKhaliilHayat
 
Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
abhikwb
 
Ad

Recently uploaded (20)

To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 

PHP and Mysql

  • 2. PHP-MySQL database applications Brief review of MySQL PHP MySQL functions examples
  • 3. Brief Review Of MySQL The MySQL comand line monitor Creating database tables Queries
  • 4. Command Line Client Read the MySQL documentation c:mysqlmysqldocsmanual_toc.html Read MySQL install instructions on CDSupply a username Command to enter monitor is and a mysql - u xxxx -p To execute an SQL script use password when prompted mysql -u xxxx -p < /path/script.sql GUI client MyCC is better
  • 5. Creating Database Tables Create web_db database to hold the tables: CREATE DATABASE web_db; To create a table called notes: USE web_db; CREATE TABLE notes (...); insert some rows for testing if necessary It is easy to write an sql script called notes.sql and use monitor to execute it
  • 6. The Basic Queries CREATE create databases and tables SELECT select table rows based on certain conditions DELETE delete one or more rows of a table INSERT insert a new row in a table UPDATE update rows in a table ALTER alter the structure of a table
  • 7. PHP MySQL Functions Connecting to a Database Making a query Using results of a query freeing resources closing the connection
  • 8. Connecting To A Database mysql_connect(server, username, password) connects to a MySQL server through a port the default is the string "localhost:3306" username is a string for the user name password is a string for the password returns FALSE on failure Example $db_link = mysql_connect("localhost:3306", "test", "123"); there is also the persistent mysql_pconnect
  • 9. Example From PHP Docs <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); print ("Connected successfully"); mysql_close($link); ?>
  • 10. Selecting A Database mysql_select_db(name, link) select a database given by the string name the link is optional and specifies the open link value such as $db_link returned by a connect statement. if not supplied the last opened link is used. returns TRUE on success else FALSE Example mysql_select_db("web_db");
  • 11. Example From PHP Docs <?php $lnk = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die ('Not connected : ' . mysql_error()); // make foo the current db mysql_select_db('foo', $lnk) or die ('Can't use foo : ' . mysql_error()); ?>
  • 12. Error Reporting (1) mysql_error(link) Return an error string or error number the link is optional if not supplied the last opened link is used. Empty string is returned if there is no error. Example mysql_error();
  • 13. Error Reporting (2) mysql_no(link) Return the error number the link is optional if not supplied the last opened link is used. 0 is returned if there is no error. Example mysql_no();
  • 14. Example From PHP Docs <?php mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb"); echo mysql_errno() . ": " . mysql_error(). "n"; mysql_select_db("kossu"); mysql_query("SELECT * FROM nonexistenttable"); echo mysql_errno() . ": " . mysql_error() . "n"; ?>
  • 15. Making A Query (1) mysql_query(query, link) make a select query (link is optional) query is a string for the MySQL query Don't end the query with a semi-colon Return value is a resource identifier or FALSE if the query is SELECT, SHOW or DESCRIBE Example (select all rows of books table) $query = "SELECT * FROM books"; $result = mysql_query($query);
  • 16. Making A Query (2) INSERT and UPDATE queries for these queries a resource is not returned TRUE is returned on sucess FALSE is returned on failure Example (describe the books table) $query = "DESCRIBE books"; $status = mysql_query($query);
  • 17. Example From PHP Docs <?php $result = mysql_query("SELECT my_col FROM my_tbl") or die("Invalid query: " . mysql_error()); ?>
  • 18. Retrieving Table Information mysql_list_fields(database, table, link) For a select query it retrieves information from given table in given database. link is optional The returned resource can be used to obtain properties of the table such as names of the table columns and field type information Example $fields = mysql_list_fields("web_db", "books");
  • 19. Number Of Table Columns mysql_num_fields(result) return the numbers of columns in a table result is the resource returned by a call to the mysql_list_fields function Example $fields = mysql_list_fields("web_db", "books"); $num_columns = mysql_num_fields($fields);
  • 20. Names Of Table Columns mysql_field_name(result, index) return the name of the table column whose position is given by index (0,1,...) result is the resource returned by a call to mysql_list_fields Example: the first column name $fields = mysql_list_fields("web_db", "books"); $isbn = mysql_field_name($fields, 0);
  • 21. Example From PHP Docs <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $fields = mysql_list_fields("database1", "table1", $link); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { echo mysql_field_name($fields, $i) . "n"; } ?>
  • 22. Accessing Table Rows (1) mysql_fetch_row(result) each call returns the next row as an indexed array where result is a resource returned from a call to mysql_query (FALSE if no more rows) Example $query = "SELECT * FROM books"; $result = mysql_query($query); $row = mysql_fetch_row($result); // row 0 $isbn = $row[0]; // isbn for row 0
  • 23. Accessing Table Rows (2) mysql_fetch_assoc(result) as in mysql_fetch_row but next row is returned as an associative array Example $query = "SELECT * FROM books"; $result = mysql_query($query); $row = mysql_fetch_assoc($result); // row 0 $isbn = $row['isbn']; // isbn for row 0
  • 24. Accessing Table Rows (3) mysql_fetch_array(result) combines mysql_fetch_row, mysql_fetch_assoc returns row information as both an associative array and an indexed array Example $query = "SELECT * FROM books"; $result = mysql_query($query); $row = mysql_fetch_array($result); // row 0 $isbnA = $row[0]; // isbn for row 0 $isbnB = $row['isbn']; // can also get it this way
  • 25. Accessing table rows (4) mysql_num_rows(result) returns number of rows from a select query result is the resource returned by the select query mysql_affected_rows(result) used after an INSERT, UPDATE, or DELETE query to return the number of rows affected result is the resource returned
  • 26. Other Functions mysql_real_escape_string(string,link) returns a string safe to use in mysql_query In MySQL 4.1 there are mysqli_... functions which are supposed to be improved. There are many other MySQL functions that we will not use. See PHP function reference for complete list
  • 27. Freeing Resources mysql_free_result(result) free memory associated with the given resource called result (after a select query). Not necessary except for large result sets Done automatically when script exits. mysql_close(link) close the database connection associated with the given link doesn't do anything for persistent links.
  • 28. Processing column names // Get resource for the field names $fields = mysql_list_fields("web_db", "books"); // Get number of table columns $num_cols = mysql_num_fields($fields); // process them using a for loop for ($i = 0; $i < $num_cols; $i++) { $name = mysql_field_name($fields, $i) // do something here with $name }
  • 29. Processing table rows (1) while ($row = mysql_fetch_array($result) { From SELECT for ($i = 0; $i < count($row); *i++) query { $col_value = $row[$i]' // Do something with $col_value here } // do end of row processing here } // do end of table processing here Here $row is returned as an array so the inner loop is a for loop
  • 30. Processing table rows (2) while ($row = mysql_fetch_assoc($result) { From SELECT foreach($row as $col_value) query { // Do something with $col_value here } // do end of row processing here } // do end of table processing here Here $row is returned as an associated array so the inner loop is a foreach loop. The foreach is easier to use.
  • 31. A db_connect Function This function can be used in scripts to connect to a database. Put it in a file called db_connect.php in your include path <?php function db_connect($db_name) { $host_name = "localhost:3306"; $user_name = "xxxxx"; $password = "yyyyy"; $db_link = mysql_connect($host_name, $user_name, $password) or die("Could not connect to $host_name"); mysql_select_db($db_name) or die("Could not select database $db_name"); return $db_link; } ?>
  • 32. Books Display Example (1) First create the following books.sql file containing a sample database table CREATE DATABASE IF NOT EXISTS web_db; USE web_db; CREATE TABLE books ( isbn title author pub year price ); CHAR(15) VARCHAR(100) VARCHAR(100) VARCHAR(20) year DECIMAL(9,2) PRIMARY KEY NOT NULL, NOT NULL, NOT NULL, NOT NULL, NOT NULL, DEFAULT NULL
  • 33. Books Display Example (2) books.sql continued (insert some books) INSERT INTO books VALUES ( '0-672-31784-2', 'PHP and MySQL Web Development', 'Luke Welling, Laura Thomson', 'Sams', 2001, 74.95 ); Insert a few more (see simplebooks.sql)
  • 34. Books Display Example (3) Run books.sql through MySQL using the command mysql -u xxxxx -p < c:/.../books.sql Or use the gui client MyCC here xxxxx is your MySQL username and the -p option means to prompt for the password Now write a PHP script called dbase.php that displays the books in an HTML table
  • 36. dbase.php (1) HTML header information <?php require_once("db_connect.php"); ?> <html> <head> <title> Displaying the book database table using PHP </title> <h1>Displaying thebook database table using PHP</h1> <?php
  • 37. dbase.php (2) Make a database connection $db_link = db_connect("web_db"); This uses the function defined in the include file db_connect.php My include path in php.ini is include_path=".;c:Apachephpincludes" current directory
  • 38. dbase.php (3) Send a SELECT query for all columns $query = "SELECT * FROM books"; $result = mysql_query($query) or die("SQL Query failed"); Obtain table properties $fields = mysql_list_fields("web_db", "books"); $num_columns = mysql_num_fields($fields)
  • 39. dbase.php (4) Display column headings in an HTML table echo '<table border="1">', "n"; echo "<tr>n"; for ($i = 0; $i < $num_columns; $i++) { echo "<th>", mysql_field_name($fields, $i), "</th>n"; } echo "</tr>n";
  • 40. dbase.php (5) Display the books table in as an HTML table while ($row = mysql_fetch_assoc($result)) { echo "<tr>n"; foreach ($row as $col_value) { echo "<td>$col_value</td>n"; } echo "</tr>n"; } echo "</table>n";
  • 41. dbase.php (6) Free resources and close connection mysql_free_result($result); mysql_close($db_link); ?> </body> </html> view script dbase.php http://localhost/users/MYSQL/dbase.php
  • 42. Calling Script From Button (1) Give the button a name and a value <input type="submit" name="choice" value="Display"> When form is submitted the name will exist if (isset($_REQUEST['choice']) { // process the button click here } ... Multiple submit buttons should have different names or same name, different values
  • 43. Calling Script From Button (2) Another approach is to use the submit button label (value) to distinquish choices $choice = isset($_REQUEST['choice']) ? $_REQUEST['choice'] : ""; if ($choice == "Display") { // process the button click here } ... Multiple submit buttons can have the same name but different labels (values)
  • 44. Calling Script From Link A link can be clicked to invoke the script again or to pass a parameter to it using the GET method (query string in link) <?php $this_url = $_SERVER['PHP_SELF']; $edit_url = "$this_url?choice=edit&id=$id"; $delete_url = "$this_url?choice=delete&id=$id"; ?> <a href="<?php echo $edit_url?>">[ Edit ]</a> <a href="<?php echo $delete_url?>">[ Delete ]</a>
  • 45. Suggestion Box Users make suggestions through a textarea in a form and submit them Suggestion is saved in a MySQL database table called sbox in database web_db Suggestions are displayed along with the time view script sbox/sbox.php http://localhost/php/MYSQL/sbox/sbox.php
  • 47. sbox.sql CREATE DATABASE IF NOT EXITS web_db; USE web_db; DROP TABLE IF EXISTS sbox; CREATE TABLE sbox ( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, time DATETIME NOT NULL, suggestion TEXT NOT NULL ); view script sbox/sbox.sql
  • 48. Script Logic IF request for new suggestion THEN display form to get new suggestion ELSE IF form was submitted THEN insert suggestion into database table ENDIF Retrieve suggestions from database table IF there are suggestions THEN display them ELSE Suggestion table is empty ENDIF ENDIF provide self link to enter a new suggestion
  • 49. sbox.php (1) <?php require_once("db_connect.php"); ?> <html><head><title>Suggestion Box</title></head> <body><h1>Suggestion Box</h1> <?php $self = $_SERVER['PHP_SELF']; if (isset($_REQUEST['new'])) // link was clicked { ?> <form action="<?php echo $self ?>" method="POST"> Enter your suggestion:<br> <textarea name="suggestion" rows="5" cols="50" </textarea><br> <p><input type="submit" name="add" value="Submit"></p> </form> <?php }
  • 50. sbox.php (2) else { $db_link = db_connect("web_db"); if (isset($_REQUEST['add'])) { $suggestion = $_REQUEST['suggestion']; $query = "INSERT INTO sbox SET time=NOW()," . "suggestion='$suggestion'"; mysql_query($query); } Forgot to use addslashes and stripslashes
  • 51. sbox.php (3) // Display all the suggestions $query = "SELECT time, suggestion FROM sbox"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $time = $row['time']; $suggestion = $row['suggestion']; echo "<b>$time:</b> $suggesion<br>n"; } } else
  • 52. sbox.php (4) { echo "The suggestion box is empty"; } ?> <p><a href="<?php echo $self ?>?new=1"> Submit a new suggestion</a></p> </body> </html> <?php } A trick for ?> calling a script from a link with a view script sbox/sbox.php parameter
  • 53. Other Versions There are versions sbox2, sbox3, sbox4 sbox2 handles quotes and HTML text properly sbox3 adds error checking sbox4 is a simpler version of sbox3 for which the form is always displayed so no link is needed to add a new suggestion.
  • 54. sbox4.php (1) <?php require_once("db_connect.php"); $db_link = db_connect("web_db"); $self = $_SERVER['PHP_SELF']; ?> <html><head><title>Suggestion Box</title></head> <body><h1>Suggestion Box</h1> <form action="<?php echo $self ?>" method="POST"> Enter your suggestion:<br> <textarea name="suggestion" rows="5" cols="50" </textarea><br> <p><input type="submit" name="add" value="Submit"></p> </form>
  • 55. sbox4.php (2) <?php // add a new suggestion if there is one if (isset($_POST['add'])) { $suggestion = addslashes($_POST['suggestion']); if (strlen($suggestion) > 0) { $query = "INSERT INTO sbox SET time=NOW(), suggestion='$suggestion'"; mysql_query($query); } }
  • 56. sbox4.php (3) // display all the suggestions $query = "SELECT time, suggestion FROM sbox ORDER BY time DESC"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $time = $row['time']; $suggestion = htmlspecialchars(stripslashes( $row['suggestion'])); echo "<strong>$time:</strong> $suggestion<br> n"; } }
  • 57. sbox4.php (4) else { echo "The suggestion box is empty"; } ?> </body> </html>