Real escape string and PDO

PhpMysqlPdo

Php Problem Overview


I'm using PDO after migrating away from the mysql library. What do I use in place of the old real_escape_string function?

I need to escape single quotes so they will go into my database and I think there may be a better way to handle this without add(ing) slashes to all my strings. What should I be using?

Php Solutions


Solution 1 - Php

You should use PDO Prepare

From the link:

> Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

Solution 2 - Php

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

Solution 3 - Php

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - PhpSteDView Answer on Stackoverflow
Solution 2 - PhpPowerAktarView Answer on Stackoverflow
Solution 3 - PhpPiskvor left the buildingView Answer on Stackoverflow