PHP -Securing SQL Injection



$input = "I hate your website! <script
language='JavaScript'>document.location='http://www.example.com/';</script>";
echo strip_tags($input);
//I hate your website! document.location='http://www.example.com/';

SELECT * FROM info  WHERE id = '4' OR 1=1//SQL injection

Solution of sql injection Prepared statements......
// Prepare query, identifying one dynamic parameter (identified by the ?)
$query = $db->prepare("SELECT * FROM games WHERE id = ?");
// Tell MySQL the provided variable will be an integer(i)
$query->bind_param('i', $_GET['id']);
// Execute the query
$query->execute();


$stmt->bind_param('s', $_POST['title']);//s=string


6 CHAPTER 4 • INTRODUCING MYSQL
01 <?php
02
03 require_once('config.inc.php');
04
05 $sql = 'SELECT id, title FROM platforms ORDER BY title';
06
07 $query = $db->prepare($sql);
08
09 $query->execute();
10
11 $query->store_result();
12
13 $query->bind_result($id, $title);
14
15 while($query->fetch()) {
16 echo "{$id}: {$title}<br />";
17 }
18
19 $query->free_result();
20 $query->close();
21
22 ?>

A breakdown follows:
• Line 05 specifies the query, which retrieves all platforms in alphabetical order.
• Line 07 and 09 prepares and executes the query, respectively. You'll notice this process is
identical to that used when preparing queries dependent upon user input (as discussed earlier
in this chapter).
• Line 11 stores the query results within server memory. This is known as buffering the result
set, which is in contrast to working with an unbuffered result set. Throughout this chapter
we'll use the former approach, which is fine when working with small and medium-sized
query results, and comes with the bonus of a few additional features which you'll learn about
later. See the below sidebar, "Buffered vs. Unbuffered Results" for more information about
this topic.
• Line 13 assigns (or binds) two variables to the corresponding columns retrieved from the
query (Line 05).
• Line 15 retrieves each row from the returned result set, assigning the column values in that
row to the $id and $title variables, respectively. Line 16 in turn outputs the $id and $title
variables to the browser.
• Lines 19 and 20 returns the memory used to store the result, and closes the statement. These
calls are not strictly required, since PHP will automatically perform these tasks once the script
completes execution. However if your script includes several prepared statements, you should
explicitly complete these tasks at the appropriate locations.

Reactions: