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?

1

1 Answer 1

6

Read about pdo prepared statements

Here is an example

$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@skwee stackoverflow.com/questions/5741187/… says that only PDO prepared statements can't prevent injection. take a look at this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.