0

Possible Duplicate:
How to prevent SQL injection in PHP?

I have this code

$where = '';
if (isset($_POST['lvl']) && $vals = $_POST['lvl']) {
    $where = 'WHERE ';
$first = false;
if ($vals[0] === '0') {
    $where .= 'team = "neutral"';
    unset($vals[0]);
    $first = true;
}
if (count($vals)) {
    if ($first) $where .= ' OR ';
    $where .= 'lvl IN (\'' . implode('\',\'', $vals) . '\')';
}}
    $sql = "SELECT * FROM $table $where";
$res = $DBH->prepare($sql);
$res->execute();
$num = $res->rowCount();
echo "<h2>".$num."</h2>";

It works, but if someone did something, then this happens. How to fix this?

UPD: added PDO code

Community
  • 1
  • 1
user1955915
  • 39
  • 1
  • 6

3 Answers3

0

Use PHP's mysqli_real_escape_string() in order to escape values. Note that it is mysqli because mysql functions have been depreciated.

Ryan Tse
  • 1,559
  • 11
  • 15
0

You need to use PDO::quote() for all string values.
Also you should never select all the records when you need only to count them. Ask a database to do it for you

$where = '';
if (!empty($_POST['lvl'])) {
    $vals = $_POST['lvl'];
    $where = 'WHERE ';
    if ($vals[0] === '0') {
        $where .= "team = 'neutral'";
        unset($vals[0]);
        if ($vals) {
            $where .= " OR ";
        }
    }
    if ($vals) {
        foreach ($vals as $i => $val) {
           $vals[$i] = $DBH->quote($val);
        }
        $where .= "lvl IN (".implode(',', $vals).")";
    }
}
$sql = "SELECT count(*) as cnt FROM $table $where";
$res = $DBH->query($sql);
$res->execute();
$row = $res->fetch();
echo "<h2>".$row['num']."</h2>";

By the way, with my own class the code would be slightly less complex, because it makes manual escaping unnecessary (it is using mysqli, not PDO though).

$where = '';
if (!empty($_POST['lvl'])) {
    $vals = $_POST['lvl'];
    $where = 'WHERE ';
    if ($vals[0] === '0') {
        $where .= "team = 'neutral'";
        unset($vals[0]);
        if ($vals) {
            $where .= " OR ";
        }
    }
    if ($vals) {
        $where .= $db->parse("lvl IN (?a)",$vals);
    }
}
$num = $db->getOne("SELECT count(*) as cnt FROM ?n ?p",$table, $where);
echo "<h2>".$num."</h2>";
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • rowCount is proof that code works and do right things. Original code receives all from db and creates many html code. Anyway, thanks, first code block is that i need. – user1955915 Jan 26 '13 at 09:21
-1

Use PDO with named parameters

http://php.net/manual/en/pdo.prepared-statements.php

Ayaz
  • 376
  • 1
  • 3
  • 14