Insert form in MySQL with PDO [duplicate]

This is more or less the simplest way to run an update using PDO:

// database connection
$conn = new PDO("mysql:host=localhost;dbname=MyDBName",aDBUser,aDBPassword);

// Disable emulated prepared statements 
// PDO will **TRY** to use real (non-emaulated) prepared statements
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Some sample data
$aTitle="PHP Security";
$anAuthor="John Doe";

// Prepare a statement with some placeholders prefixed by ':'
$sql = "INSERT "
     . "  INTO books "
     . "       ( title, author   ) "
     . "VALUES ( :title, :author )"
     ;
$q = $conn->prepare($sql);

// Execute the prepared statement and replace placeholders by values
$q->execute(array(':author' => $anAuthor,
                  ':title'  => $aTitle
                 )
           );

Additionally, you might wish to review OWASP‘s PHP Security Cheat Sheet.

Security consideration

If the DB-driver isn’t able to use native prepared statements, it falls back to emulated prepared statements (which might be less secure). From the docs:

PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared
statements. Some drivers do not support native prepared statements or
have limited support for them. Use this setting to force PDO to either
always emulate prepared statements (if TRUE), or to try to use native
prepared statements (if FALSE). It will always fall back to emulating
the prepared statement if the driver cannot successfully prepare the
current query. Requires bool.

Leave a Comment