wawanopoulos
wawanopoulos

Reputation: 9804

PDO : Need to escape string or not ?

I use this code to insert some data into my database. I adapt my previous code based on mysqli to use PDO now.

For the 2 parameters name and id, do i need to escape them using a function like mysqli_real_escape_string with PDO ? or is it OK to pass these params direclty in the query ?

<?php
try
{  
    $pdo = new   PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);

    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $json = $_POST['jsonData'];
    $id = $json["id"]
    $name = $json["name"]

    $pdo->beginTransaction();

    // do request

    $pdo->query('INSERT INTO test(id, name) VALUES ('$id', '$name')');

    $pdo->commit();

    echo 'Everything is OK';
}
catch(Exception $e)
{
    $pdo->rollback();

    echo 'An error occurred :<br />';
    echo 'Error : '.$e->getMessage().'<br />';
    echo 'N° : '.$e->getCode();

    exit();
}

Upvotes: 1

Views: 4965

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 158005

You don't have to escape strings but you have to use preared statements.

Here is what your code should be.

<?php
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$json = $_POST['jsonData'];

$pdo->prepare('INSERT INTO test(id, name) VALUES (:id,:name)')->execute($json);
echo 'Everything is OK';

note that a transaction is useless for just a single query and the way you are reporting errors is wrong.

also, if $json already contains the all the data for thequery, no need to store its contents in separate variables.

Upvotes: 1

s1h4d0w
s1h4d0w

Reputation: 781

You need to prepare your statement, try this:

$query = $pdo->prepare('INSERT INTO test(id, name) VALUES (:theid, :thename)');
$query->execute(array(
    'theid' => $id,
    'thename' => $name
));

Upvotes: 4

Shira
Shira

Reputation: 6570

It's not okay. You need to use prepared statements or PDO::quote().

Upvotes: 0

Related Questions