0% found this document useful (0 votes)
50 views

Sistemas de Informação e Bases de Dados: PHP and SQL

This document provides an overview of how PHP can interact with SQL databases. It discusses how PHP supports connecting to databases through extensions and abstraction layers. It covers typical interactions like opening a database connection, executing SQL statements, iterating through result sets, and closing connections. It also addresses dynamically generating forms, security concerns around SQL injection, and how to protect against injection using prepared statements.

Uploaded by

Ricardo Trindade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Sistemas de Informação e Bases de Dados: PHP and SQL

This document provides an overview of how PHP can interact with SQL databases. It discusses how PHP supports connecting to databases through extensions and abstraction layers. It covers typical interactions like opening a database connection, executing SQL statements, iterating through result sets, and closing connections. It also addresses dynamically generating forms, security concerns around SQL injection, and how to protect against injection using prepared statements.

Uploaded by

Ricardo Trindade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Sistemas de Informao e Bases de Dados

PHP and SQL

PHP and SQL


Web-based information system

Presentation

Operations

Storage

Web browser

Web server

Database

(e.g. Firefox on
your laptop)

(e.g. Apache on
sigma.ist.utl.pt)

(e.g. MySQL on
db.ist.utl.pt)

HTML, CSS, etc.

PHP and others

SQL

PHP and SQL


PHP supports many database systems
through vendor-specific database extensions
DB2, Informix, MySQL, Oracle, PostgreSQL, SQL Server,
SQLite, Sybase...
through database abstraction layers
dbx, ODBC, PDO, Pear DB...

PHP and SQL


PHP Data Objects (PDO)
single interface for accessing several databases
built-in extension in PHP 5.1+
object-oriented interface

PHP and SQL


Typical interaction between PHP and SQL

open database connection


execute SQL statement
iterate through the results
close the connection

PHP and SQL


Opening a database connection
requires connection string or DSN (data source name)
"mysql:host=db.ist.utl.pt;dbname=istxxxxxx"

requires username and password


'istxxxxxx'

'aaaa0000'

PHP and SQL


Executing a SQL statement
if the statement returns a result set (e.g. select)
query("select ...");

if the statement does not return a result set (e.g. update)


exec("update ...");

PHP and SQL


Iterating through the results
result set may be very large, impossible to get everything
at once, iterate through the results one-by-one
SQL query
Web server
(PHP)

Database server
(MySQL)

PHP and SQL


Iterating through the results
result set may be very large, impossible to get everything
at once, iterate through the results one-by-one
SQL query
Web server
(PHP)

cursor

Database server
(MySQL)

PHP and SQL


Iterating through the results
result set may be very large, impossible to get everything
at once, iterate through the results one-by-one
SQL query
Web server
(PHP)

cursor
fetch
array

Database server
(MySQL)
1

PHP and SQL


Iterating through the results
result set may be very large, impossible to get everything
at once, iterate through the results one-by-one
SQL query
Web server
(PHP)

cursor
fetch
array

Database server
(MySQL)

PHP and SQL


Iterating through the results
result set may be very large, impossible to get everything
at once, iterate through the results one-by-one
SQL query
Web server
(PHP)

cursor
fetch

array

Database server
(MySQL)

PHP and SQL


Closing the connection
often a source of big trouble, because there is a limit to
the number of connections (typically 400 or so)

Web server
(PHP)
sigma.ist.utl.pt

Database server
(MySQL)
db.ist.utl.pt

PHP and SQL


Opening the connection
<?php

$host = "db.ist.utl.pt";
$user = "istxxxxxx";
$pass = "aaaa0000";
$dsn = "mysql:host=$host;dbname=$user";

$connection = new PDO($dsn, $user, $pass);


...

PHP and SQL


Opening the connection
testing if something went wrong
try
{
$connection = new PDO($dsn, $user, $pass);

}
catch(PDOException $exception)
{
echo("<p>Error: ");
echo($exception->getMessage());
echo("</p>");
exit();
}
Error: SQLSTATE[28000] [1045] Access denied for user
'istxxxxxx'@'sigma01.ist.utl.pt' (using password: YES)

PHP and SQL


Executing a SQL statement
$sql = "SELECT * FROM account";
$result = $connection->query($sql);

PHP and SQL


Executing a SQL statement
checking if something went wrong
$result = $connection->query($sql);
if ($result == FALSE)
{
$info = $connection->errorInfo();
echo("<p>Error: {$info[2]}</p>");
exit();
}
Error: Table 'istxxxxxx.account' doesn't exist

PHP and SQL


Executing a SQL statement
number of rows and columns
$result = $connection->query($sql);
$nrows = $result->rowCount();
echo("<p>Number of rows: $nrows</p>");
$ncols = $result->columnCount();
echo("<p>Number of columns: $ncols</p>");
Number of rows: 7
Number of columns: 3

PHP and SQL


Iterating through the results
$result = $connection->query($sql);

Array

foreach($result as $row)
{
echo("<p>$row</p>");
}

Array
Array
Array

Array
Array
Array

PHP and SQL


Iterating through the results
$result = $connection->query($sql);

A-101Downtown500.00

foreach($result as $row)
{
echo("<p>");
echo($row['account_number']);
echo($row['branch_name']);
echo($row['balance']);
echo("</p>");
}

A-102Perryridge400.00
A-201Brighton900.00
A-215Mianus700.00

A-217Brighton750.00
A-222Redwood700.00
A-305Round Hill350.00

PHP and SQL


Iterating through the results
displaying the results as a table
echo("<table border=\"1\">");
echo("<tr><td>account_number</td><td>branch_name</td>
<td>balance</td></tr>");
foreach($result as $row)
{
echo("<tr><td>");
echo($row['account_number']);
echo("</td><td>");
echo($row['branch_name']);
echo("</td><td>");
echo($row['balance']);
echo("</td></tr>");
}
echo("</table>");

PHP and SQL


Closing the connection
$connection = NULL;

PHP and SQL


Beyond the basics

processing forms
dynamically-generated forms
security (SQL injection)
prepared statements

PHP and SQL


Processing forms
<html>
<body>
<form action="insert.php">
<h3>Insert a new account</h3>
<p>Account no.: <input type="text" name="account_number"/></p>
<p>Branch: <input type="text" name="branch_name"/></p>
<p>Balance: <input type="text" name="balance"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>

PHP and SQL


Processing forms
...
$account_number = $_REQUEST['account_number'];
$branch_name = $_REQUEST['branch_name'];
$balance = $_REQUEST['balance'];

$connection = new PDO($dsn, $user, $pass);


$sql = "INSERT INTO account VALUES ('$account_number',
'$branch_name', $balance)";
$nrows = $connection->exec($sql);
echo("<p>Rows inserted: $nrows</p>");
...

Static form
<html>
<body>
<form action="insert.php" method="post">
<h3>Insert a new account</h3>
<p>Account no.: <input type="text" name="account_number"/></p>
<p>Branch:
<select name="branch_name">
<option value="Brighton">Brighton</option>
<option value="Downtown">Downtown</option>
<option value="Mianus">Mianus</option>
<option value="North Town">North Town</option>
<option value="Perryridge">Perryridge</option>
<option value="Pownal">Pownal</option>
<option value="Redwood">Redwood</option>
<option value="Round Hill">Round Hill</option>
</select>
</p>
<p>Balance: <input type="text" name="balance"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>

Dynamically-generated form
<html>
<body>
<form action="insert.php" method="post">
<h3>Insert a new account</h3>
<p>Account no.: <input type="text" name="account_number"/></p>
<p>Branch:
<select name="branch_name">
<?php
$connection = new PDO($dsn, $user, $pass);
$sql = "SELECT branch_name FROM branch ORDER BY branch_name";
$result = $connection->query($sql);
foreach($result as $row)
{
$branch_name = $row['branch_name'];
echo("<option value=\"$branch_name\">$branch_name</option>");
}
?>
</select>
</p>
<p>Balance: <input type="text" name="balance"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>

PHP and SQL


Security (SQL injection)
...
$account_number = $_REQUEST['account_number'];
$branch_name = $_REQUEST['branch_name'];
$balance = $_REQUEST['balance'];

$connection = new PDO($dsn, $user, $pass);


$sql = "INSERT INTO account VALUES ('$account_number',
'$branch_name', $balance)";
$nrows = $connection->exec($sql);
echo("<p>Rows inserted: $nrows</p>");
...

PHP and SQL


Security (SQL injection)
...
$account_number = $_REQUEST['account_number'];
$branch_name = $_REQUEST['branch_name'];
$balance = $_REQUEST['balance'];

$connection = new PDO($dsn, $user, $pass);


$sql = "INSERT INTO account VALUES ('$account_number',
'$branch_name', $balance)";
$nrows = $connection->exec($sql);

INSERTecho("<p>Rows
INTO account inserted:
VALUES ('A-215',
'Perryridge', 400)
$nrows</p>");
...

PHP and SQL


Security (SQL injection)
...
$account_number = $_REQUEST['account_number'];
$branch_name = $_REQUEST['branch_name'];
$balance = $_REQUEST['balance'];

$connection = new PDO($dsn, $user, $pass);


$sql = "INSERT INTO account VALUES ('$account_number',
'$branch_name', $balance)";
$nrows = $connection->exec($sql);

INSERTecho("<p>Rows
INTO account inserted:
VALUES ('A-125',
'Perryridge', 400);
$nrows</p>");
DROP TABLE
... depositor; --)

PHP and SQL


How to protect against SQL injection
use prepared statements
...
$account_number = $_REQUEST['account_number'];
$branch_name = $_REQUEST['branch_name'];
$balance = $_REQUEST['balance'];
$stmt = $connection->prepare("INSERT INTO account
VALUES (:account_number, :branch_name, :balance)");
$stmt->bindParam(':account_number', $account_number);
$stmt->bindParam(':branch_name', $branch_name);
$stmt->bindParam(':balance', $balance);
$stmt->execute();
...

PHP and SQL


How to protect against SQL injection
use prepared statements
...
$account_number = $_REQUEST['account_number'];
$stmt = $connection->prepare("SELECT balance FROM
account WHERE account_number=:account_number");
$stmt->bindParam(':account_number', $account_number);
$stmt->execute();

foreach($stmt as $row)
{
echo($row['balance']);
}
...

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy