-1

I have a function which generates a query. Something like this:

// this is a simplified version of my real code
public function get_query(){
    $name = $_GET['name'];
    return "SELECT * FROM mytable WHERE name = $name";
}

As you know, such queries aren't safe. Because they are threatened by SQL injection. Anyway, I need to escape $name variable before using it into the query.

Well there are two approaches: (since I use PDO. Otherwise there is also an old way which is using mysql_escape_string())

  1. Using PDO::prepare()
  2. Using PDO::quote()

Both of them need the PDO connection which isn't access into the generator query function. Now I want to know, is there any other approach?

FirstOne
  • 6,033
  • 7
  • 26
  • 45
Martin AJ
  • 6,261
  • 8
  • 53
  • 111

1 Answers1

2

Yes. You could have the function return something that will later be used with PDO. Since you said it's not available in generation time, do any step needed beforehand, then use PDO, because well, you'll have to, some time.

Where PDO is not available:

public function get_query(){
    $name = $_GET['name'];
    return array(
        'query' => 'SELECT * FROM mytable WHERE name = :name',
        'params' => array(':name', $name)
    );
}

Where PDO is available:

// pass '$values' to a class where a connection is available
$values = get_query();
$pdo->prepare($values['query']); // $pdo->prepare('SELECT * FROM mytable WHERE name = :name');
$pdo->execute($values['params']); // $pdo->execute(array(':name', value_of_$name));

It would look like the Second Example from the Manual. It will allow you to still use prepared statements with parameterized queries, even without knowing what query / parameters are being used.


Some notes:

  • Escaping is not enough to prevent sql injection;
  • This won't change much of your original idea, since you'd still pass to PDO the generated query returned from get_query();
  • In case your query generation is too complex, you could just use ? in the query as unnamed parameters - similar to example 3 from the manual - provided the values are passed in the correct order.
FirstOne
  • 6,033
  • 7
  • 26
  • 45