-
Notifications
You must be signed in to change notification settings - Fork 2
/
products.php
42 lines (41 loc) · 1.54 KB
/
products.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
error_reporting(E_ALL & ~E_DEPRECATED); // ~E_DEPRECATED because mysql extension is deprecated since PHP 5.5
include '../config/config.php';
if ($pdo) {
// Use PDO
$database = new PDO("mysql:host=$dbHost;dbname=$dbSchema", $dbUsername, $dbPassword);
if (isset($_GET['id'])) {
$statement = $database->prepare('SELECT id, name, description, image FROM products WHERE id = ?');
$statement->execute(array($_GET['id']));
} else {
$statement = $database->query('SELECT id, name, description, image FROM products ORDER BY name');
}
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
} else {
// If you can't use PDO
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbSchema);
mysql_set_charset('utf8');
if (isset($_GET['id'])) {
$id = $_GET['id']; // WRONG, vulnerable to SQL Injection attack
$id = mysql_real_escape_string($_GET['id']); // WRONG, still vulnerable to SQL Injection attack
// $id = (int)$_GET['id']; // CORRECT, SQL query expects a number not a string, that's why escaping is not enough
$sql = "SELECT id, name, description, image FROM products WHERE id = $id";
} else {
$sql = "SELECT id, name, description, image FROM products ORDER BY name";
}
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
}
echo '<ul>';
foreach ($rows as $row) {
printf('<li><a href="?id=%s">%s</a>(%s)</li>',
htmlspecialchars($row['id']),
htmlspecialchars($row['name']),
htmlspecialchars($row['description'])
);
}
echo '<ul>';