PDO security question PHP

3

I would like to know the difference in security level of the two code snippets below:

// TRECHO 1
<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

// TRECHO 2
<?php
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories,$colour));
?>

In section 1, the bindParam() is used, already in 2 the parameters are passed directly in the execute, but also the prepare() is used.

    
asked by anonymous 13.11.2015 / 15:18

2 answers

5

In terms of safety there is no difference. One of the differences is that bindParam() besides offering parameter typing ( PDO::PARAM_STR , PDO::PARAM_INT etc) has other obscure features for using stored procedures. See the method signature.

  

public bool PDOStatement :: bindParam (mixed $ parameter, mixed & $ variable [ int $ data_type = PDO :: PARAM_STR [ int $ length [ mixed $ driver_options]]]

When using execute() all parameters are sent as PDO::PARAM_STR the maximum that can happen is your query fails if you have placeholder in the LIMIT/OFFSET class.

Related:

What's the difference between bindParam and bindValue?

Using PDO is the safest way to connect to a DB with PHP?

    
13.11.2015 / 15:25
3

Practically and theoretically there is no difference, because if you analyze, in the first case, where you used bindParam , with placeholders of the symbolic type (?):

$sth->bindParam(1, $calories, PDO::PARAM_INT);

You used the number 1 as a reference to this placeholder.

By writing the parameters online, along with the execute method, you are not doing anything different, each value receives indexes according to the number of placeholders specified.

$sth->execute( array( 0 => 150, 1 => 'red' ) ); 

It would be the same thing to do:

$params = array(150,'red');
$sth->execute($params);

If you still have questions, I recommend you read this:

13.11.2015 / 15:31