Web Chapter 6
Web Chapter 6
SIX
Database Driven
Websites
PHP/MySQL
Understanding the MySQL Privilege
System
Locking and concurrency
Speeding up database wit indexe
queries h s
General optimization tips
Different table types
Loading data from a file
Making your database secur
more e
Web security and cryptography
theory
Static Web pages
Data is stored in .html
files
changes their
Won't change until source
someone codes
Dynamic Web
pages
Web pages that respond to users' requests
and gather
information from them. Oftentimes, they
have built-in
links to a database, from which they extract
data based
on input from the users
A database-driven Web site is a Web site that
uses a
database to gather, display, or manipulate
information
News sites: CNN.com and MSNBC.com
Example:
E-commerce companies: Amazon.com, which
is a Web interface of a big-sized database
system containing customer and
transactional
What do we needinformation.
to built a database-driven
website?
A DBMS & a scripting
language
Commercial databases: Oracle, SQL
Server
Cost:
expensive
Hardware requirements:
high
Have an impressive array of advanced
features
Open source databases: PostgreS
MySQL, QL
Cost:
cheap
Hardware
requirements: low
Lack some advanced
features
Open- scriptin languag
source g es
PH
P
JS
P
Per
l
Proprieta scripting
ry languages
ASP
Cold
.NET
Fusion
MySQL is the de-facto standard database
system for
web sites with HUGE volumes of both
data and
end-users (like Facebook, Twitter, and
Wikipedia).
mysqli_select_db(database_name
,$c on);
<?php
$servername = "localhost"; $username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username,
$password);
// Check connection
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());}
?> else echo "Connected successfully";
Equivalent to
<?
php
$conn = mysqli_connect("localhost","username", "password") or
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
PHP function for making
queries:
mysqli_query(query_strin con_resource)
g, ;
Queries that return information, such as
SELECT:
returns a result set
$resul = mysqli_query(query_strin$con)
t g, ;
In this case, the result set is stored in the
variable $result
Other queries, returns TRUE upon success
and FALSE
on failure. Best practice is to handle the error
(e.g.
die(mysql_error()))
CREATE DATABASE dbname
CREATE TABLE table_name (column_name
data_type(size), column_name data_type(size) …)
INSER INTO table_name (column1, column3,...
T column2, )
VALUE (value1, value2, value3,...)
S
column1, column2 …
FROM table_name
SELEC
T
WHERE some_column=some_value
UPDATE table_name
SET column1=value,
column2=value2,...
WHERE some_column=some_value
DELETE FROM table_name
WHERE some_column = some_value
Rules to follow while making query
strings
The SQL query must be
quoted
String values inside the SQL b
query must e
quoted
Numeric values must not be
quoted
The word NULL must not be
quoted
<?php
// Create connection
$conn = mysqli_connect("localhost", "username",
"password")
or die("Connection failed: ". mysqli_connect_error());
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
}else{
echo "Error creating database".
mysqli_error($conn);
}
mysqli_close($conn
?> );
<?php
// Create connection
$conn = mysqli_connect("localhost","username", ”mydb” or
"password“, )
die("Connection failed: ". mysqli_connect_error());
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date
TIMESTAMP)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB";
// Create
$conn = connection
mysqli_connect($servername, $username, $dbname)
$password, or
die("Connection failed: ".
mysqli_connect_error());
Example
if (mysqli_num_rows($result)
$result = mysqli_query(query,>
0) {
$con);
while ($row mysqli_fetch_assoc($result {
= ))
$col =
1 $row['column_1_name'];
=
$col $row['column_2_name'];
2 so
forth...
} //
and
}
<?php
$servername = "localhost"; $username =
"username";
$password = $dbname =
"password"; "myDB";
$conn = mysqli_connect($servername, $username, $password,
$dbname) or
die("Connection failed: ".
mysqli_connect_error());
$sql = "SELECT id, fname, lname FROM
MyGuests";
mysqli_query($conn, $sql)) or die("Error: “ .
mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id:". $row["id"]. "Name:". “.
$row[“fname"].” $row["lname"]."<br>";
}
} else {
echo "0 results";}
mysqli_close($conn);
A prepared statement is a feature used to execute
the same (or
similar) SQL statements repeatedly with high
efficiency.
Prepared statements basically work
like this:
Prepare: An SQL statement template is created and sent to
the database.
Certain values are left unspecified, called parameters
(labeled "?").
Example: INSERT INTO MyGuests VALUES(?, ?, ?)
The database parses, compiles, and performs query
optimization on the
SQL statement template, and stores the result without
executing it
Execute: At a later time, the application binds the values to
the
parameters, and the database executes the statement. The
application
may execute the statement as many times as it wants with
different values
Compared to executing SQL statements directly,
prepared
statements have two main advantages:
Prepared statements reduces parsing time as the
preparation on
the query is done only once (although the statement is
executed
multiple times)
Write
Other sessions are not allowed to acquire a WRITE lock
lock
The session that holds the lock can read and write to
the table
Only the session that holds the lock can access the
table. No other
session can access it until the lock is released
Result
The code at the server would create a valid SQL statement
like this:
SELECT * FROM Users WHERE UserId = 105; DROP
Solution
TABLEto SQL
Suppliers
injection
1 Do input screening before sending user input to a
. database
2 Use prepared statements than normal statements
.
Use addslashes() to filter data before it is passed to
a database
escapes out characters that might be troublesome to
a database
you can use the stripslashes() function to return the
data to its
Switch on form
original magic_quotes_gpc and
magic_quotes_runtime
directives in php.ini
automatically adds and strip slashes for incoming GET,
POST and
COOKIE variables to and from databases
Use the escapeshellcmd() when passing user data to
a system()
or exec() call
escapes out any meta-characters that can be used to
force the
system to run arbitrary commands entered by a
The strip_tags() strips out HTML and
PHP tags
from a string
prevents users from planting a in use
malicious script r
data
htmlspecialchars() PHP function converts
characters to HTML entities
for example, < is converted to < this function
converts any
script tags to harmless characters
trim() strips unnecessary characters
(extra space,
tab, newline) from the user input data
<?php
$name = $email = $gender = $comment =
if ($_SERVER["REQUEST_METHOD"]
$website = ""; == {
"POST")
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website =
test_input($_POST["website"]);
$gender = test_input($_POST["gender"]);
}
function
test_input($data) {
$dat =trim($data);
a =stripslashes($data);
$dat =htmlspecialchars($d
a
return ata);
}$data;
$dat
?a