0

How can I avoid mysql injections? This is the PHP file I have right now

<?php
include 'config.php';

$Name = $_GET['Name'] ;

$sql = "Select * from tables where names =\"$Name\"";



try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->query('SET CHARACTER SET utf8');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->query($sql);  
    $names = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"key":'. json_encode($names) .'}'; 
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}


?>

When I put $stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name)); to the code it doesn't work. So how should I do it?

Legionar
  • 7,472
  • 2
  • 41
  • 70
user1423276
  • 65
  • 3
  • 10
  • 2
    possible duplicate of [Best way to prevent SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) – eggyal Jun 07 '12 at 09:30

1 Answers1

6

Read about pdo prepared statements

Here is an example

$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));
Dmitry Kudryavtsev
  • 16,354
  • 4
  • 25
  • 32
  • 3
    This is very important and oft misunderstood: *just using PDO doesn't protect you from SQL injection.* Only parametrized queries like the one above do. – Pekka Jun 07 '12 at 09:30
  • @skwee http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string/12118602#12118602 says that only PDO prepared statements can't prevent injection. take a look at this. – adeel iqbal Sep 30 '13 at 12:07