update page now
Longhorn PHP 2026 - Call For Papers

Voting

: max(nine, four)?
(Example: nine)

The Note You're Voting On

ASchmidt at Anamera dot net
7 years ago
Escaping strings with control characters, quotes and backslashes for subsequent use in MySQL commands.

MySQL has documented a number of backslash escape sequences that need to be used to pass certain values in SQL commands: https://dev.mysql.com/doc/refman/5.7/en/string-literals.html

It's crucial to escape existing backslashes first to prevent double-escaping, before escaping the various control sequences:

<?php
$result = str_replace(
                array( '\\',    "\0",   "'",    "\x8" /* BS */, "\n",   "\r",   "\t",   "\x1A" /* Ctrl+Z */ ),
                array( '\\\\',  '\\0',  '\\\'', '\\b',          '\\n',  '\\r',  '\\t',  '\\Z' ),
                $value );
?>

This code is NOT intended to protect against SQL insertions, it's intended to PRESERVE string content correctly, if it contains control characters.

<< Back to user notes page

To Top