<p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p>

<pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
</code></pre>

<p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p>

<pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
</code></pre>

<p>What can be done to prevent this from happening?</p>

[{'answer_id': 60180, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 10, 'selected': False, 'text': '<p>I\'d recommend using <a href="http://ca3.php.net/manual/en/book.pdo.php" rel="noreferrer">PDO</a> (PHP Data Objects) to run parameterized SQL queries. </p>\n\n<p>Not only does this protect against SQL injection, but it also speeds up queries. </p>\n\n<p>And by using PDO rather than <code>mysql_</code>, <code>mysqli_</code>, and <code>pgsql_</code> functions, you make your application a little more abstracted from the database, in the rare occurrence that you have to switch database providers.</p>\n'}, {'answer_id': 60195, 'author': 'Tanerax', 'author_id': 567, 'author_profile': 'https://Stackoverflow.com/users/567', 'pm_score': 9, 'selected': False, 'text': '<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk.</p>\n</blockquote>\n<p>You could do something basic like this:</p>\n<pre><code>$safe_variable = mysqli_real_escape_string($dbConnection, $_POST[&quot;user-input&quot;]);\nmysqli_query($dbConnection, &quot;INSERT INTO table (column) VALUES (\'&quot; . $safe_variable . &quot;\')&quot;);\n</code></pre>\n<p>This won\'t solve every problem, but it\'s a very good stepping stone. I left out obvious items such as checking the variable\'s existence, format (numbers, letters, etc.).</p>\n'}, {'answer_id': 60442, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 11, 'selected': False, 'text': '<p>To use the parameterized query, you need to use either Mysqli or PDO. To rewrite your example with mysqli, we would need something like the following.</p>\n<pre><code>&lt;?php\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(&quot;server&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database_name&quot;);\n\n$variable = $_POST[&quot;user-input&quot;];\n$stmt = $mysqli-&gt;prepare(&quot;INSERT INTO table (column) VALUES (?)&quot;);\n// &quot;s&quot; means the database expects a string\n$stmt-&gt;bind_param(&quot;s&quot;, $variable);\n$stmt-&gt;execute();\n</code></pre>\n<p>The key function you\'ll want to read up on there would be <a href="http://php.net/mysqli.prepare" rel="noreferrer"><code>mysqli::prepare</code></a>.</p>\n<p>Also, as others have suggested, you may find it useful/easier to step up a layer of abstraction with something like <a href="http://php.net/pdo" rel="noreferrer">PDO</a>.</p>\n<p>Please note that the case you asked about is a fairly simple one and that more complex cases may require more complex approaches. In particular:</p>\n<ul>\n<li>If you want to alter the structure of the SQL based on user input, parameterized queries are not going to help, and the escaping required is not covered by <code>mysql_real_escape_string</code>. In this kind of case, you would be better off passing the user\'s input through a whitelist to ensure only \'safe\' values are allowed through.</li>\n</ul>\n'}, {'answer_id': 60496, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 14, 'selected': True, 'text': '<p>The <em>correct</em> way to avoid SQL injection attacks, no matter which database you use, is to <strong>separate the data from SQL</strong>, so that data stays data and will <strong>never be interpreted</strong> as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don\'t <em>fully</em> understand the details, you should always <strong>use prepared statements and parameterized queries.</strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.</p>\n<p>You basically have two options to achieve this:</p>\n<ol>\n<li><p>Using <a href="http://php.net/manual/en/book.pdo.php" rel="noreferrer"><strong>PDO</strong></a> (for any supported database driver):</p>\n <pre class="lang-php prettyprint-override"><code>$stmt = $pdo-&gt;prepare(\'SELECT * FROM employees WHERE name = :name\');\n$stmt-&gt;execute([ \'name\' =&gt; $name ]);\n\nforeach ($stmt as $row) {\n    // Do something with $row\n}\n</code></pre>\n</li>\n<li><p>Using <a href="http://php.net/manual/en/book.mysqli.php" rel="noreferrer"><strong>MySQLi</strong></a> (for MySQL):</p>\n <pre class="lang-php prettyprint-override"><code>$stmt = $dbConnection-&gt;prepare(\'SELECT * FROM employees WHERE name = ?\');\n$stmt-&gt;bind_param(\'s\', $name); // \'s\' specifies the variable type =&gt; \'string\'\n$stmt-&gt;execute();\n\n$result = $stmt-&gt;get_result();\nwhile ($row = $result-&gt;fetch_assoc()) {\n    // Do something with $row\n}\n</code></pre>\n</li>\n</ol>\n<p>If you\'re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, <code>pg_prepare()</code> and <code>pg_execute()</code> for PostgreSQL). PDO is the universal option.</p>\n<hr />\n<h2>Correctly setting up the connection</h2>\n<h4>PDO</h4>\n<p>Note that when using <strong>PDO</strong> to access a MySQL database <em>real</em> prepared statements are <strong>not used by default</strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using <strong>PDO</strong> is:</p>\n<pre class="lang-php prettyprint-override"><code>$dbConnection = new PDO(\'mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4\', \'user\', \'password\');\n\n$dbConnection-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n</code></pre>\n<p>In the above example, the error mode isn\'t strictly necessary, <strong>but it is advised to add it</strong>. This way PDO will inform you of all MySQL errors by means of throwing the <code>PDOException</code>.</p>\n<p>What is <strong>mandatory</strong>, however, is the first <code>setAttribute()</code> line, which tells PDO to disable emulated prepared statements and use <em>real</em> prepared statements. This makes sure the statement and the values aren\'t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).</p>\n<p>Although you can set the <code>charset</code> in the options of the constructor, it\'s important to note that \'older\' versions of PHP (before 5.3.6) <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">silently ignored the charset parameter</a> in the DSN.</p>\n<h4>Mysqli</h4>\n<p>For mysqli we have to follow the same routine:</p>\n<pre class="lang-php prettyprint-override"><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting\n$dbConnection = new mysqli(\'127.0.0.1\', \'username\', \'password\', \'test\');\n$dbConnection-&gt;set_charset(\'utf8mb4\'); // charset\n</code></pre>\n<hr />\n<h2>Explanation</h2>\n<p>The SQL statement you pass to <code>prepare</code> is parsed and compiled by the database server. By specifying parameters (either a <code>?</code> or a named parameter like <code>:name</code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute</code>, the prepared statement is combined with the parameter values you specify.</p>\n<p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn\'t intend.</p>\n<p>Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name</code> variable contains <code>\'Sarah\'; DELETE FROM employees</code> the result would simply be a search for the string <code>&quot;\'Sarah\'; DELETE FROM employees&quot;</code>, and you will not end up with <a href="http://xkcd.com/327/" rel="noreferrer">an empty table</a>.</p>\n<p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.</p>\n<p>Oh, and since you asked about how to do it for an insert, here\'s an example (using PDO):</p>\n<pre class="lang-php prettyprint-override"><code>$preparedStatement = $db-&gt;prepare(\'INSERT INTO table (column) VALUES (:column)\');\n\n$preparedStatement-&gt;execute([ \'column\' =&gt; $unsafeValue ]);\n</code></pre>\n<hr />\n<h2>Can prepared statements be used for dynamic queries?</h2>\n<p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.</p>\n<p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.</p>\n<pre><code>// Value whitelist\n// $dir can only be \'DESC\', otherwise it will be \'ASC\'\nif (empty($dir) || $dir !== \'DESC\') {\n   $dir = \'ASC\';\n}\n</code></pre>\n'}, {'answer_id': 60530, 'author': 'Imran', 'author_id': 1897, 'author_profile': 'https://Stackoverflow.com/users/1897', 'pm_score': 9, 'selected': False, 'text': "<p>Use <code>PDO</code> and prepared queries.</p>\n<p>(<code>$conn</code> is a <code>PDO</code> object)</p>\n<pre><code>$stmt = $conn-&gt;prepare(&quot;INSERT INTO tbl VALUES(:id, :name)&quot;);\n$stmt-&gt;bindValue(':id', $id);\n$stmt-&gt;bindValue(':name', $name);\n$stmt-&gt;execute();\n</code></pre>\n"}, {'answer_id': 348719, 'author': 'Rob', 'author_id': 3542, 'author_profile': 'https://Stackoverflow.com/users/3542', 'pm_score': 9, 'selected': False, 'text': "<p>Whatever you do end up using, make sure that you check your input hasn't already been mangled by <code>magic_quotes</code> or some other well-meaning rubbish, and if necessary, run it through <code>stripslashes</code> or whatever to sanitize it.</p>\n"}, {'answer_id': 1669109, 'author': 'Nikhil', 'author_id': 14944, 'author_profile': 'https://Stackoverflow.com/users/14944', 'pm_score': 8, 'selected': False, 'text': '<p>I favor <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedures</a> (<a href="http://dev.mysql.com/doc/refman/5.1/en/stored-routines-syntax.html" rel="noreferrer">MySQL has had stored procedures support since 5.0</a>) from a security point of view - the advantages are -</p>\n\n<ol>\n<li>Most databases (including <a href="http://dev.mysql.com/doc/refman/5.1/en/stored-routines-privileges.html" rel="noreferrer">MySQL</a>) enable user access to be restricted to executing stored procedures. The fine-grained security access control is useful to prevent escalation of privileges attacks. This prevents compromised applications from being able to run SQL directly against the database.</li>\n<li>They abstract the raw SQL query from the application so less information of the database structure is available to the application. This makes it harder for people to understand the underlying structure of the database and design suitable attacks.</li>\n<li>They accept only parameters, so the advantages of parameterized queries are there. Of course - IMO you still need to sanitize your input - especially if you are using dynamic SQL inside the stored procedure.</li>\n</ol>\n\n<p>The disadvantages are -</p>\n\n<ol>\n<li>They (stored procedures) are tough to maintain and tend to multiply very quickly. This makes managing them an issue.</li>\n<li>They are not very suitable for dynamic queries - if they are built to accept dynamic code as parameters then a lot of the advantages are negated.</li>\n</ol>\n'}, {'answer_id': 6381189, 'author': 'rahularyansharma', 'author_id': 779158, 'author_profile': 'https://Stackoverflow.com/users/779158', 'pm_score': 9, 'selected': False, 'text': '<blockquote>\n  <p><strong>Deprecated Warning:</strong>\n  This answer\'s sample code (like the question\'s sample code) uses PHP\'s <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n  \n  <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n  \n  <p><strong>IMPORTANT</strong></p>\n  \n  <p>The best way to prevent SQL Injection is to use <strong>Prepared Statements</strong> <em>instead of escaping</em>, as <a href="https://stackoverflow.com/a/60496/2224584">the accepted answer</a> demonstrates. </p>\n  \n  <p>There are libraries such as <a href="https://github.com/auraphp/Aura.Sql" rel="noreferrer">Aura.Sql</a> and <a href="https://github.com/paragonie/easydb" rel="noreferrer">EasyDB</a> that allow developers to use prepared statements easier. To learn more about why prepared statements are better at <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">stopping SQL injection</a>, refer to <a href="https://stackoverflow.com/a/12118602/2224584">this <code>mysql_real_escape_string()</code> bypass</a> and <a href="https://kraft.im/2015/05/how-emoji-saved-your-sites-hide/" rel="noreferrer">recently fixed Unicode SQL Injection vulnerabilities in WordPress</a>.</p>\n</blockquote>\n\n<p>Injection prevention - <a href="http://php.net/manual/en/function.mysql-real-escape-string.php" rel="noreferrer">mysql_real_escape_string()</a></p>\n\n<p>PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function, <code>mysql_real_escape_string</code>.</p>\n\n<p><code>mysql_real_escape_string</code> takes a string that is going to be used in a MySQL query and return the same string with all SQL injection attempts safely escaped. Basically, it will replace those troublesome quotes(\') a user might enter with a MySQL-safe substitute, an escaped quote \\\'.</p>\n\n<p><strong>NOTE:</strong> you must be connected to the database to use this function!</p>\n\n<p>// Connect to MySQL</p>\n\n<pre><code>$name_bad = "\' OR 1\'"; \n\n$name_bad = mysql_real_escape_string($name_bad);\n\n$query_bad = "SELECT * FROM customers WHERE username = \'$name_bad\'";\necho "Escaped Bad Injection: &lt;br /&gt;" . $query_bad . "&lt;br /&gt;";\n\n\n$name_evil = "\'; DELETE FROM customers WHERE 1 or username = \'"; \n\n$name_evil = mysql_real_escape_string($name_evil);\n\n$query_evil = "SELECT * FROM customers WHERE username = \'$name_evil\'";\necho "Escaped Evil Injection: &lt;br /&gt;" . $query_evil;\n</code></pre>\n\n<p>You can find more details in <em><a href="http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php" rel="noreferrer">MySQL - SQL Injection Prevention</a></em>.</p>\n'}, {'answer_id': 6565763, 'author': 'Cedric', 'author_id': 154607, 'author_profile': 'https://Stackoverflow.com/users/154607', 'pm_score': 9, 'selected': False, 'text': '<blockquote>\n  <p><strong>Deprecated Warning:</strong>\n  This answer\'s sample code (like the question\'s sample code) uses PHP\'s <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n  \n  <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n\n<p>Parameterized query AND input validation is the way to go. There are many scenarios under which SQL injection may occur, even though <code>mysql_real_escape_string()</code> has been used.</p>\n\n<p>Those examples are vulnerable to SQL injection:</p>\n\n<pre><code>$offset = isset($_GET[\'o\']) ? $_GET[\'o\'] : 0;\n$offset = mysql_real_escape_string($offset);\nRunQuery("SELECT userid, username FROM sql_injection_test LIMIT $offset, 10");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$order = isset($_GET[\'o\']) ? $_GET[\'o\'] : \'userid\';\n$order = mysql_real_escape_string($order);\nRunQuery("SELECT userid, username FROM sql_injection_test ORDER BY `$order`");\n</code></pre>\n\n<p>In both cases, you can\'t use <code>\'</code> to protect the encapsulation.</p>\n\n<p><a href="http://www.webappsec.org/projects/articles/091007.txt" rel="noreferrer">Source</a>: <em>The Unexpected SQL Injection (When Escaping Is Not Enough)</em></p>\n'}, {'answer_id': 8255054, 'author': 'Your Common Sense', 'author_id': 285587, 'author_profile': 'https://Stackoverflow.com/users/285587', 'pm_score': 10, 'selected': False, 'text': '<p>Every answer here covers only part of the problem.\nIn fact, there are <strong>four</strong> different query parts which we can add to SQL dynamically: -</p>\n<ul>\n<li>a string</li>\n<li>a number</li>\n<li>an identifier</li>\n<li>a syntax keyword</li>\n</ul>\n<p>And prepared statements cover only two of them.</p>\n<p>But sometimes we have to make our query even more dynamic, adding operators or identifiers as well.\nSo, we will need different protection techniques.</p>\n<p>In general, such a protection approach is based on <em>whitelisting</em>.</p>\n<p>In this case, every dynamic parameter should be hardcoded in your script and chosen from that set.\nFor example, to do dynamic ordering:</p>\n<pre><code>$orders  = array(&quot;name&quot;, &quot;price&quot;, &quot;qty&quot;); // Field names\n$key = array_search($_GET[\'sort\'], $orders)); // if we have such a name\n$orderby = $orders[$key]; // If not, first one will be set automatically. \n$query = &quot;SELECT * FROM `table` ORDER BY $orderby&quot;; // Value is safe\n</code></pre>\n<p>To ease the process I wrote a <a href="https://phpdelusions.net/pdo_examples/order_by" rel="noreferrer">whitelist helper function</a> that does all the job in one line:</p>\n<pre><code>$orderby = white_list($_GET[\'orderby\'], &quot;name&quot;, [&quot;name&quot;,&quot;price&quot;,&quot;qty&quot;], &quot;Invalid field name&quot;);\n$query  = &quot;SELECT * FROM `table` ORDER BY `$orderby`&quot;; // sound and safe\n</code></pre>\n<p>There is another way to secure identifiers - escaping but I rather stick to whitelisting as a more robust and explicit approach. Yet as long as you have an identifier quoted, you can escape the quote character to make it safe. For example, by default for mysql you have to <a href="https://dev.mysql.com/doc/refman/8.0/en/identifiers.html" rel="noreferrer">double the quote character to escape it</a>. For other other DBMS escaping rules would be different.</p>\n<p>Still, there is an issue with SQL syntax keywords (such as <code>AND</code>, <code>DESC</code> and such), but white-listing seems the only approach in this case.</p>\n<p>So, a general recommendation may be phrased as</p>\n<blockquote>\n<ul>\n<li>Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) must be added through a prepared statement. No Exceptions.</li>\n<li>Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.</li>\n</ul>\n</blockquote>\n<h3>Update</h3>\n<p>Although there is a general agreement on the best practices regarding SQL injection protection, there are <strong>still many bad practices as well.</strong> And some of them too deeply rooted in the minds of PHP users. For instance, on this very page there are (although invisible to most visitors) <strong>more than 80 deleted answers</strong> - all removed by the community due to bad quality or promoting bad and outdated practices. Worse yet, some of the bad answers aren\'t deleted, but rather prospering.</p>\n<p>For example, <a href="https://stackoverflow.com/a/11802479">there(1)</a> <a href="https://stackoverflow.com/a/6381189">are(2)</a> <a href="https://stackoverflow.com/a/60195/">still(3)</a> <a href="https://stackoverflow.com/a/12426697/">many(4)</a> <a href="https://stackoverflow.com/a/21179234">answers(5)</a>, including the <a href="https://stackoverflow.com/a/60442">second most upvoted answer</a> suggesting you manual string escaping - an outdated approach that is proven to be insecure.</p>\n<p>Or there is a slightly better answer that suggests just <a href="https://stackoverflow.com/a/12710285">another method of string formatting</a> and even boasts it as the ultimate panacea. While of course, it is not. This method is no better than regular string formatting, yet it keeps all its drawbacks: it is applicable to strings only and, like any other manual formatting, it\'s essentially optional, non-obligatory measure, prone to human error of any sort.</p>\n<p>I think that all this because of one very old superstition, supported by such authorities like <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_4:_Escaping_All_User_Supplied_Input" rel="noreferrer">OWASP</a> or <a href="http://php.net/manual/en/function.mysql-real-escape-string.php#refsect1-function.mysql-real-escape-string-description" rel="noreferrer">the PHP manual</a>, which proclaims equality between whatever &quot;escaping&quot; and protection from SQL injections.</p>\n<p>Regardless of what PHP manual said for ages, <strong><code>*_escape_string</code> by no means makes data safe</strong> and never has been intended to. Besides being useless for any SQL part other than string, manual escaping is wrong, because it is manual as opposite to automated.</p>\n<p>And OWASP makes it even worse, stressing on escaping <em>user input</em> which is an utter nonsense: there should be no such words in the context of injection protection. Every variable is potentially dangerous - no matter the source! Or, in other words - every variable has to be properly formatted to be put into a query - no matter the source again. It\'s the destination that matters. The moment a developer starts to separate the sheep from the goats (thinking whether some particular variable is &quot;safe&quot; or not) he/she takes his/her first step towards disaster. Not to mention that even the wording suggests bulk escaping at the entry point, resembling the very magic quotes feature - already despised, deprecated and removed.</p>\n<p>So, unlike whatever &quot;escaping&quot;, prepared statements <em>is</em> the measure that indeed protects from SQL injection (when applicable).</p>\n'}, {'answer_id': 10992656, 'author': 'devOp', 'author_id': 842330, 'author_profile': 'https://Stackoverflow.com/users/842330', 'pm_score': 8, 'selected': False, 'text': '<p>If possible, cast the types of your parameters. But it\'s only working on simple types like int, bool, and float.</p>\n\n<pre><code>$unsafe_variable = $_POST[\'user_id\'];\n\n$safe_variable = (int)$unsafe_variable ;\n\nmysqli_query($conn, "INSERT INTO table (column) VALUES (\'" . $safe_variable . "\')");\n</code></pre>\n'}, {'answer_id': 11308776, 'author': 'Johannes Fahrenkrug', 'author_id': 171933, 'author_profile': 'https://Stackoverflow.com/users/171933', 'pm_score': 8, 'selected': False, 'text': '<p>In my opinion, the best way to generally prevent SQL injection in your PHP application (or any web application, for that matter) is to think about your application\'s architecture. If the only way to protect against SQL injection is to remember to use a special method or function that does The Right Thing every time you talk to the database, you are doing it wrong. That way, it\'s just a matter of time until you forget to correctly format your query at some point in your code.</p>\n\n<p>Adopting the MVC pattern and a framework like <a href="http://cakephp.org/" rel="noreferrer">CakePHP</a> or <a href="http://codeigniter.com/" rel="noreferrer">CodeIgniter</a> is probably the right way to go: Common tasks like creating secure database queries have been solved and centrally implemented in such frameworks. They help you to organize your web application in a sensible way and make you think more about loading and saving objects than about securely constructing single SQL queries. </p>\n'}, {'answer_id': 11610605, 'author': 'Manish Shrivastava', 'author_id': 1133932, 'author_profile': 'https://Stackoverflow.com/users/1133932', 'pm_score': 8, 'selected': False, 'text': '<p>There are many ways of preventing SQL injections and other SQL hacks. You can easily find it on the Internet (Google Search). Of course <strong>PDO is one of the good solutions.</strong> But I would like to suggest you some good links prevention from SQL injection.</p>\n\n<p><em><a href="http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php" rel="noreferrer">What is SQL injection and how to prevent</a></em></p>\n\n<p><em><a href="https://php.net/manual/en/security.database.sql-injection.php" rel="noreferrer">PHP manual for SQL injection</a></em></p>\n\n<p><em><a href="https://learn.microsoft.com/en-gb/archive/blogs/brian_swan/whats-the-right-way-to-prevent-sql-injection-in-php-scripts" rel="noreferrer">Microsoft explanation of SQL injection and prevention in PHP</a></em></p>\n\n<p>And some other like <em><a href="https://web.archive.org/web/20190221025712/http://www.digifuzz.net/archives/2007/07/preventing-sql-injection-with-php/" rel="noreferrer">Preventing SQL injection with MySQL and PHP</a></em>.</p>\n\n<p>Now, <strong>why you do you need to prevent your query from SQL injection?</strong></p>\n\n<p>I would like to let you know: Why do we try for preventing SQL injection with a short example below:</p>\n\n<p>Query for login authentication match:</p>\n\n<pre><code>$query="select * from users where email=\'".$_POST[\'email\']."\' and password=\'".$_POST[\'password\']."\' ";\n</code></pre>\n\n<p>Now, if someone (a hacker) puts</p>\n\n<pre><code>$_POST[\'email\']= admin@emali.com\' OR \'1=1\n</code></pre>\n\n<p>and password anything....</p>\n\n<p>The query will be parsed into the system only up to:</p>\n\n<pre><code>$query="select * from users where email=\'admin@emali.com\' OR \'1=1\';\n</code></pre>\n\n<p>The other part will be discarded. So, what will happen? A non-authorized user (hacker) will be able to log in as administrator without having his/her password. Now, he/she can do anything that the administrator/email person can do. See, it\'s very dangerous if SQL injection is not prevented.</p>\n'}, {'answer_id': 11802479, 'author': 'Nicolas Finelli', 'author_id': 1720432, 'author_profile': 'https://Stackoverflow.com/users/1720432', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="nofollow noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n<blockquote>\n<p><strong>Warning</strong>: The mysql extension is removed at this time. we recommend using the <em>PDO extension</em></p>\n</blockquote>\n<p>Using this PHP function <code>mysql_escape_string()</code> you can get a good prevention in a fast way.</p>\n<p>For example:</p>\n<pre><code>SELECT * FROM users WHERE name = \'&quot;.mysql_escape_string($name_from_html_form).&quot;\'\n</code></pre>\n<p><code>mysql_escape_string</code> — Escapes a string for use in a mysql_query</p>\n<p>For more prevention, you can add at the end ...</p>\n<pre><code>wHERE 1=1   or  LIMIT 1\n</code></pre>\n<p>Finally you get:</p>\n<pre><code>SELECT * FROM users WHERE name = \'&quot;.mysql_escape_string($name_from_html_form).&quot;\' LIMIT 1\n</code></pre>\n'}, {'answer_id': 12426697, 'author': 'Soumalya Banerjee', 'author_id': 1019484, 'author_profile': 'https://Stackoverflow.com/users/1019484', 'pm_score': 7, 'selected': False, 'text': '<blockquote>\n  <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n  \n  <p><strong>Deprecated Warning</strong>: The mysql extension is deprecated at this time. we recommend using the <em>PDO extension</em></p>\n</blockquote>\n\n<p>I use three different ways to prevent my web application from being vulnerable to SQL injection.</p>\n\n<ol>\n<li>Use of <code>mysql_real_escape_string()</code>, which is a pre-defined function in <a href="http://en.wikipedia.org/wiki/PHP" rel="noreferrer">PHP</a>, and this code add backslashes to the following characters: <code>\\x00</code>, <code>\\n</code>, <code>\\r</code>, <code>\\</code>, <code>\'</code>, <code>"</code> and <code>\\x1a</code>. Pass the input values as parameters to minimize the chance of SQL injection.</li>\n<li>The most advanced way is to use PDOs.</li>\n</ol>\n\n<p>I hope this will help you.</p>\n\n<p>Consider the following query:</p>\n\n<p><code>$iId = mysql_real_escape_string("1 OR 1=1");\n $sSql = "SELECT * FROM table WHERE id = $iId";</code></p>\n\n<p>mysql_real_escape_string() will not protect here. If you use single quotes (\' \') around your variables inside your query is what protects you against this. Here is an solution below for this:</p>\n\n<p><code>$iId = (int) mysql_real_escape_string("1 OR 1=1");\n $sSql = "SELECT * FROM table WHERE id = $iId";</code></p>\n\n<p>This <a href="https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string">question</a> has some good answers about this.</p>\n\n<p>I suggest, using PDO is the best option.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p><code>mysql_real_escape_string()</code> is deprecated as of PHP 5.5.0. Use either mysqli or PDO.</p>\n\n<p>An alternative to mysql_real_escape_string() is </p>\n\n<pre><code>string mysqli_real_escape_string ( mysqli $link , string $escapestr )\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>$iId = $mysqli-&gt;real_escape_string("1 OR 1=1");\n$mysqli-&gt;query("SELECT * FROM table WHERE id = $iId");\n</code></pre>\n'}, {'answer_id': 12500462, 'author': 'Xeoncross', 'author_id': 99923, 'author_profile': 'https://Stackoverflow.com/users/99923', 'pm_score': 8, 'selected': False, 'text': '<p>For those unsure of how to use PDO (coming from the <code>mysql_</code> functions), I made a <a href="https://github.com/Xeoncross/DByte/blob/master/DByte/DB.php" rel="noreferrer">very, very simple PDO wrapper</a> that is a single file. It exists to show how easy it is to do all the common things applications need to be done. Works with PostgreSQL, MySQL, and SQLite.</p>\n<p>Basically, read it <a href="http://php.net/pdo" rel="noreferrer">while you read the manual</a> to see how to put the PDO functions to use in real life to make it simple to store and retrieve values in the format <strong>you</strong> want.</p>\n<blockquote>\n<p><strong>I want a single column</strong></p>\n<pre><code>$count = DB::column(\'SELECT COUNT(*) FROM `user`\');\n</code></pre>\n<p><strong>I want an array(key =&gt; value) results (i.e. for making a selectbox)</strong></p>\n<pre class="lang-php prettyprint-override"><code>$pairs = DB::pairs(\'SELECT `id`, `username` FROM `user`\');\n</code></pre>\n<p><strong>I want a single row result</strong></p>\n<pre><code>$user = DB::row(\'SELECT * FROM `user` WHERE `id` = ?\', array($user_id));\n</code></pre>\n<p><strong>I want an array of results</strong></p>\n<pre><code>$banned_users = DB::fetch(\'SELECT * FROM `user` WHERE `banned` = ?\', array(\'TRUE\'));\n</code></pre>\n</blockquote>\n'}, {'answer_id': 12710285, 'author': 'Zaffy', 'author_id': 823738, 'author_profile': 'https://Stackoverflow.com/users/823738', 'pm_score': 9, 'selected': False, 'text': '<p>As you can see, people suggest you use prepared statements at the most. It\'s not wrong, but when your query is executed <strong>just once</strong> per process, there would be a slight performance penalty. </p>\n\n<p>I was facing this issue, but I think I solved it in <em>very</em> sophisticated way - the way hackers use to avoid using quotes. I used this in conjunction with emulated prepared statements. I use it to prevent <em>all</em> kinds of possible SQL injection attacks.</p>\n\n<h2>My approach:</h2>\n\n<ul>\n<li><p>If you expect input to be integer make sure it\'s <strong><em>really</em></strong> integer. In a variable-type language like PHP it is this <em>very</em> important. You can use for example this very simple but powerful solution: <code>sprintf("SELECT 1,2,3 FROM table WHERE 4 = %u", $input);</code>  </p></li>\n<li><p>If you expect anything else from integer <strong>hex it</strong>. If you hex it, you will perfectly escape all input. In C/C++ there\'s a function called <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-hex-string.html" rel="noreferrer"><code>mysql_hex_string()</code></a>, in PHP you can use <a href="http://www.php.net/manual/en/function.bin2hex.php" rel="noreferrer"><code>bin2hex()</code></a>.</p>\n\n<p>Don\'t worry about that the escaped string will have a 2x size of its original length because even if you use <code>mysql_real_escape_string</code>, PHP has to allocate same capacity <code>((2*input_length)+1)</code>, which is the same.</p></li>\n<li><p>This hex method is often used when you transfer binary data, but I see no reason why not use it on all data to prevent SQL injection attacks. Note that you have to prepend data with <code>0x</code> or use the MySQL function <code>UNHEX</code> instead.</p></li>\n</ul>\n\n<p>So, for example, the query:</p>\n\n<pre><code>SELECT password FROM users WHERE name = \'root\';\n</code></pre>\n\n<p>Will become:</p>\n\n<pre><code>SELECT password FROM users WHERE name = 0x726f6f74;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT password FROM users WHERE name = UNHEX(\'726f6f74\');\n</code></pre>\n\n<p>Hex is the perfect escape. No way to inject.</p>\n\n<h2>Difference between UNHEX function and 0x prefix</h2>\n\n<p>There was some discussion in comments, so I finally want to make it clear. These two approaches are very similar, but they are a little different in some ways:</p>\n\n<p>The <code>0x</code> prefix can only be used for data columns such as <code>char</code>, <code>varchar</code>, <code>text</code>, <code>block</code>, <code>binary</code>, etc.<br>\nAlso, its use is a little complicated if you are about to insert an empty string. You\'ll have to entirely replace it with <code>\'\'</code>, or you\'ll get an error.</p>\n\n<p><code>UNHEX()</code> works on <strong>any</strong> column; you do not have to worry about the empty string.</p>\n\n<hr>\n\n<h2>Hex methods are often used as attacks</h2>\n\n<p>Note that this hex method is often used as an SQL injection attack where integers are just like strings and escaped just with <code>mysql_real_escape_string</code>. Then you can avoid the use of quotes.</p>\n\n<p>For example, if you just do something like this:</p>\n\n<pre><code>"SELECT title FROM article WHERE id = " . mysql_real_escape_string($_GET["id"])\n</code></pre>\n\n<p>an attack can inject you very <em>easily</em>. Consider the following injected code returned from your script:</p>\n\n<pre><code>SELECT ... WHERE id = -1 UNION ALL SELECT table_name FROM information_schema.tables;\n</code></pre>\n\n<p>and now just extract table structure:</p>\n\n<pre><code>SELECT ... WHERE id = -1 UNION ALL SELECT column_name FROM information_schema.column WHERE table_name = __0x61727469636c65__;\n</code></pre>\n\n<p>And then just select whatever data ones want. Isn\'t it cool?</p>\n\n<p>But if the coder of an injectable site would hex it, no injection would be possible because the query would look like this:</p>\n\n<pre><code>SELECT ... WHERE id = UNHEX(\'2d312075...3635\');\n</code></pre>\n'}, {'answer_id': 12822319, 'author': 'RDK', 'author_id': 1032750, 'author_profile': 'https://Stackoverflow.com/users/1032750', 'pm_score': 8, 'selected': False, 'text': '<p>I think if someone wants to use PHP and MySQL or some other dataBase server:</p>\n<ol>\n<li>Think about learning <a href="http://php.net/manual/en/book.pdo.php" rel="nofollow noreferrer">PDO</a> (PHP Data Objects) – it is a database access layer providing a uniform method of access to multiple databases.</li>\n<li>Think about learning <a href="http://en.wikipedia.org/wiki/MySQLi" rel="nofollow noreferrer">MySQLi</a></li>\n</ol>\n<hr />\n<p><strong>Libraries examples:</strong></p>\n<p>---- <strong>PDO</strong></p>\n<blockquote>\n<p>----- No placeholders - ripe for SQL injection! <strong>It\'s bad</strong></p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) values ($name, $addr, $city)&quot;);\n</code></pre>\n<blockquote>\n<p>----- Unnamed placeholders</p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) values (?, ?, ?);\n</code></pre>\n<blockquote>\n<p>----- Named placeholders</p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) value (:name, :addr, :city)&quot;);\n</code></pre>\n<p>--- <strong>MySQLi</strong></p>\n<pre><code>$request = $mysqliConnection-&gt;prepare(\'\n       SELECT * FROM trainers\n       WHERE name = ?\n       AND email = ?\n       AND last_login &gt; ?\');\n\n    $query-&gt;bind_param(\'first_param\', \'second_param\', $mail, time() - 3600);\n    $query-&gt;execute();\n</code></pre>\n<hr />\n<p><strong>P.S</strong>:</p>\n<p>PDO wins this battle with ease. With support for twelve\ndifferent database drivers and named parameters, we can get used to its API. From a security standpoint, both of them are safe as long as the developer uses them the way they are supposed to be used</p>\n'}, {'answer_id': 13064261, 'author': 'Apurv Nerlekar', 'author_id': 1266952, 'author_profile': 'https://Stackoverflow.com/users/1266952', 'pm_score': 8, 'selected': False, 'text': '<p>The simple alternative to this problem could be solved by granting appropriate permissions in the database itself.\nFor example: if you are using a MySQL database then enter into the database through terminal or the UI provided and just follow this command:</p>\n\n<pre><code> GRANT SELECT, INSERT, DELETE ON database TO username@\'localhost\' IDENTIFIED BY \'password\';\n</code></pre>\n\n<p>This will restrict the user to only get confined with the specified query\'s only. Remove the delete permission and so the data would never get deleted from the query fired from the PHP page.\nThe second thing to do is to flush the privileges so that the MySQL refreshes the permissions and updates.</p>\n\n<pre><code>FLUSH PRIVILEGES; \n</code></pre>\n\n<p>more information about <a href="https://dev.mysql.com/doc/refman/5.7/en/flush.html" rel="noreferrer">flush</a>.</p>\n\n<p>To see the current privileges for the user fire the following query.</p>\n\n<pre><code>select * from mysql.user where User=\'username\';\n</code></pre>\n\n<p>Learn more about <a href="https://dev.mysql.com/doc/refman/5.7/en/grant.html" rel="noreferrer">GRANT</a>.</p>\n'}, {'answer_id': 14569797, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': False, 'text': '<p>Regarding many useful answers, I hope to add some value to this thread.</p>\n\n<p>SQL injection is an attack that can be done through user inputs (inputs that filled by a user and then used inside queries). The SQL injection patterns are correct query syntax while we can call it: bad queries for bad reasons, and we assume that there might be a bad person that try to get secret information (bypassing access control) that affect the three principles of security (confidentiality, integrity, and availability).</p>\n\n<p>Now, our point is to prevent security threats such as SQL injection attacks, the question asking (how to prevent an SQL injection attack using PHP), be more realistic, data filtering or clearing input data is the case when using user-input data inside such query, using PHP or any other programming language is not the case, or as recommended by more people to use modern technology such as prepared statement or any other tools that currently supporting SQL injection prevention, consider that these tools not available anymore? How do you secure your application?</p>\n\n<p>My approach against SQL injection is: clearing user-input data before sending it to the database (before using it inside any query).</p>\n\n<p><strong>Data filtering for (converting unsafe data to safe data)</strong></p>\n\n<p>Consider that <a href="http://en.wikipedia.org/wiki/PHP#History" rel="noreferrer">PDO</a> and <a href="http://en.wikipedia.org/wiki/MySQLi" rel="noreferrer">MySQLi</a> are not available. How can you secure your application? Do you force me to use them? What about other languages other than PHP? I prefer to provide general ideas as it can be used for wider border, not just for a specific language.</p>\n\n<ol>\n<li>SQL user (limiting user privilege): most common SQL operations are (SELECT, UPDATE, INSERT), then, why give the UPDATE privilege to a user that does not require it? For example, <strong>login, and search pages</strong> are only using SELECT, then, why use DB users in these pages with high privileges?</li>\n</ol>\n\n<p><strong>RULE: do not create one database user for all privileges. For all SQL operations, you can create your scheme like (deluser, selectuser, updateuser) as usernames for easy usage.</strong></p>\n\n<p>See <a href="http://en.wikipedia.org/wiki/Principle_of_least_privilege" rel="noreferrer">principle of least privilege</a>.</p>\n\n<ol start="2">\n<li><p>Data filtering: before building any query user input, it should be validated and filtered. For programmers, it\'s important to define some properties for each user-input variables:\n<strong>data type, data pattern, and data length</strong>. A field that is a number between (x and y) must be exactly validated using the exact rule, and for a field that is a string (text): pattern is the case, for example, a username must contain only some characters, let’s say [a-zA-Z0-9_-.]. The length varies between (x and n) where x and n (integers, x &lt;=n).\n<strong>Rule: creating exact filters and validation rules are best practices for me.</strong></p></li>\n<li><p>Use other tools: Here, I will also agree with you that a prepared statement (parametrized query) and stored procedures. The disadvantages here is these ways require advanced skills which do not exist for most users. The basic idea here is to distinguish between the SQL query and the data that is used inside. Both approaches can be used even with unsafe data, because the user-input data here does not add anything to the original query, such as (any or x=x).</p></li>\n</ol>\n\n<p>For more information, please read <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet" rel="noreferrer">OWASP SQL Injection Prevention Cheat Sheet</a>.</p>\n\n<p>Now, if you are an advanced user, start using this defense as you like, but, for beginners, if they can\'t quickly implement a stored procedure and prepared the statement, it\'s better to filter input data as much they can.</p>\n\n<p>Finally, let\'s consider that a user sends this text below instead of entering his/her username:</p>\n\n<pre><code>[1] UNION SELECT IF(SUBSTRING(Password,1,1)=\'2\',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = \'root\'\n</code></pre>\n\n<p>This input can be checked early without any prepared statement and stored procedures, but to be on the safe side, using them starts after user-data filtering and validation.</p>\n\n<p>The last point is detecting unexpected behavior which requires more effort and complexity; it\'s not recommended for normal web applications.</p>\n\n<p>Unexpected behavior in the above user input is SELECT, UNION, IF, SUBSTRING, BENCHMARK, SHA, and root. Once these words detected, you can avoid the input.</p>\n\n<h2>UPDATE 1:</h2>\n\n<p>A user commented that this post is useless, OK! Here is what <a href="https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_3:_Escaping_All_User_Supplied_Input" rel="noreferrer">OWASP.ORG provided</a>:</p>\n\n<blockquote>\n  <p>Primary defenses: <br/>\n   <br/>\n      Option #1: Use of Prepared Statements (Parameterized Queries) <br/>\n      Option #2: Use of Stored Procedures <br/>\n      Option #3: Escaping all User Supplied Input  <br/>\n   <br/>\n  Additional defenses: <br/>\n   <br/>\n      Also Enforce: Least Privilege <br/>\n      Also Perform: White List Input Validation <br/></p>\n</blockquote>\n\n<p>As you may know, claiming an article should be supported by a valid argument, at least by one reference! Otherwise, it\'s considered as an attack and a bad claim!</p>\n\n<h2>Update 2:</h2>\n\n<p>From the PHP manual, <a href="http://php.net/manual/en/mysqli.quickstart.prepared-statements.php" rel="noreferrer">PHP: Prepared Statements - Manual</a>:</p>\n\n<blockquote>\n  <p>Escaping and SQL injection <br/></p>\n  \n  <p>Bound variables will be escaped automatically by the server. The\n  server inserts their escaped values at the appropriate places into the\n  statement template before execution. A hint must be provided to the\n  server for the type of bound variable, to create an appropriate\n  conversion. See the mysqli_stmt_bind_param() function for more\n  information. <br/></p>\n  \n  <p>The automatic escaping of values within the server is sometimes\n  considered a security feature to prevent SQL injection. The same\n  degree of security can be achieved with non-prepared statements if\n  input values are escaped correctly. <br/></p>\n</blockquote>\n\n<h2>Update 3:</h2>\n\n<p>I created test cases for knowing how PDO and MySQLi send the query to the MySQL server when using a prepared statement:</p>\n\n<p><strong>PDO:</strong></p>\n\n<pre><code>$user = "\'\'1\'\'"; // Malicious keyword\n$sql = \'SELECT * FROM awa_user WHERE userame =:username\';\n$sth = $dbh-&gt;prepare($sql, array(PDO::ATTR_CURSOR =&gt; PDO::CURSOR_FWDONLY));\n$sth-&gt;execute(array(\':username\' =&gt; $user));\n</code></pre>\n\n<p><strong>Query Log:</strong></p>\n\n<blockquote>\n<pre><code>    189 Query SELECT * FROM awa_user WHERE userame =\'\\\'\\\'1\\\'\\\'\'\n    189 Quit\n</code></pre>\n</blockquote>\n\n<p><strong>MySQLi:</strong></p>\n\n<pre><code>$stmt = $mysqli-&gt;prepare("SELECT * FROM awa_user WHERE username =?")) {\n$stmt-&gt;bind_param("s", $user);\n$user = "\'\'1\'\'";\n$stmt-&gt;execute();\n</code></pre>\n\n<p><strong>Query Log:</strong></p>\n\n<blockquote>\n<pre><code>    188 Prepare   SELECT * FROM awa_user WHERE username =?\n    188 Execute   SELECT * FROM awa_user WHERE username =\'\\\'\\\'1\\\'\\\'\'\n    188 Quit\n</code></pre>\n</blockquote>\n\n<h3>It\'s clear that a prepared statement is also escaping the data, nothing else.</h3>\n\n<p>As also mentioned in the above statement,</p>\n\n<blockquote>\n  <p>The automatic escaping of values within the server is sometimes considered a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly</p>\n</blockquote>\n\n<p>Therefore, this proves that data validation such as <code>intval()</code> is a good idea for integer values before sending any query. In addition, preventing malicious user data before sending the query is <strong>a correct and valid approach</strong>.</p>\n\n<p>Please see this question for more detail: <em><a href="https://stackoverflow.com/questions/18026088/pdo-sends-raw-query-to-mysql-while-mysqli-sends-prepared-query-both-produce-the">PDO sends raw query to MySQL while Mysqli sends prepared query, both produce the same result</a></em></p>\n\n<p>References:</p>\n\n<ol>\n<li><a href="http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/#UnionInjections" rel="noreferrer">SQL Injection Cheat Sheet</a></li>\n<li><a href="https://www.owasp.org/index.php/SQL_Injection" rel="noreferrer">SQL Injection</a></li>\n<li><a href="http://en.wikipedia.org/wiki/Information_security" rel="noreferrer">Information security</a></li>\n<li><a href="http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/security-principles.html" rel="noreferrer">Security Principles</a></li>\n<li><a href="http://en.wikipedia.org/wiki/Data_validation" rel="noreferrer">Data validation</a></li>\n</ol>\n'}, {'answer_id': 15805869, 'author': '5ervant - techintel.github.io', 'author_id': 2007055, 'author_profile': 'https://Stackoverflow.com/users/2007055', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Warning: the approach described in this answer only applies to very specific scenarios and isn\'t secure since SQL injection attacks do not only rely on being able to inject <code>X=Y</code>.</strong></p>\n\n<p>If the attackers are trying to hack into the form via PHP\'s <code>$_GET</code> variable or with the URL\'s query string, you would be able to catch them if they\'re not secure.</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ([0-9]+)=([0-9]+)\nRewriteRule ^(.*) ^/track.php\n</code></pre>\n\n<p>Because <code>1=1</code>, <code>2=2</code>, <code>1=2</code>, <code>2=1</code>, <code>1+1=2</code>, etc... are the common questions to an SQL database of an attacker. Maybe also it\'s used by many hacking applications.</p>\n\n<p>But you must be careful, that you must not rewrite a safe query from your site. The code above is giving you a tip, to rewrite or redirect <em>(it depends on you)</em> that hacking-specific dynamic query string into a page that will store the attacker\'s <a href="http://en.wikipedia.org/wiki/IP_address" rel="noreferrer">IP address</a>, or EVEN THEIR COOKIES, history, browser, or any other sensitive information, so you can deal with them later by banning their account or contacting authorities.</p>\n'}, {'answer_id': 16466714, 'author': 'Danijel', 'author_id': 2352773, 'author_profile': 'https://Stackoverflow.com/users/2352773', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="nofollow noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead.</p>\n</blockquote>\n<p>A few guidelines for escaping special characters in SQL statements.</p>\n<p>Don\'t use <a href="http://www.php.net/manual/en/intro.mysql.php" rel="nofollow noreferrer">MySQL</a>. This extension is deprecated. Use <a href="http://php.net/manual/en/book.mysqli.php" rel="nofollow noreferrer">MySQLi</a> or <a href="http://php.net/manual/en/book.pdo.php" rel="nofollow noreferrer">PDO</a> instead.</p>\n<p><strong>MySQLi</strong></p>\n<p>For manually escaping special characters in a string you can use the <a href="http://www.php.net/manual/en/mysqli.real-escape-string.php" rel="nofollow noreferrer">mysqli_real_escape_string</a> function. The function will not work properly unless the correct character set is set with <a href="http://www.php.net/manual/en/mysqli.set-charset.php" rel="nofollow noreferrer">mysqli_set_charset</a>.</p>\n<p>Example:</p>\n<pre><code>$mysqli = new mysqli(\'host\', \'user\', \'password\', \'database\');\n$mysqli-&gt;set_charset(\'charset\');\n\n$string = $mysqli-&gt;real_escape_string($string);\n$mysqli-&gt;query(&quot;INSERT INTO table (column) VALUES (\'$string\')&quot;);\n</code></pre>\n<p>For automatic escaping of values with prepared statements, use <a href="http://www.php.net/manual/en/mysqli.prepare.php" rel="nofollow noreferrer">mysqli_prepare</a>, and <a href="http://www.php.net/manual/en/mysqli-stmt.bind-param.php" rel="nofollow noreferrer">mysqli_stmt_bind_param</a> where types for the corresponding bind variables must be provided for an appropriate conversion:</p>\n<p>Example:</p>\n<pre><code>$stmt = $mysqli-&gt;prepare(&quot;INSERT INTO table (column1, column2) VALUES (?,?)&quot;);\n\n$stmt-&gt;bind_param(&quot;is&quot;, $integer, $string);\n\n$stmt-&gt;execute();\n</code></pre>\n<p>No matter if you use prepared statements or <code>mysqli_real_escape_string</code>, you always have to know the type of input data you\'re working with.</p>\n<p>So if you use a prepared statement, you must specify the types of the variables for <code>mysqli_stmt_bind_param</code> function.</p>\n<p>And the use of <code>mysqli_real_escape_string</code> is for, as the name says, escaping special characters in a string, so it will not make integers safe. The purpose of this function is to prevent breaking the strings in SQL statements, and the damage to the database that it could cause. <code>mysqli_real_escape_string</code> is a useful function when used properly, especially when combined with <code>sprintf</code>.</p>\n<p>Example:</p>\n<pre><code>$string = &quot;x\' OR name LIKE \'%John%&quot;;\n$integer = \'5 OR id != 0\';\n\n$query = sprintf( &quot;SELECT id, email, pass, name FROM members WHERE email =\'%s\' AND id = %d&quot;, $mysqli-&gt;real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email =\'x\\\' OR name LIKE \\\'%John%\' AND id = 5\n\n$integer = \'99999999999999999999\';\n$query = sprintf(&quot;SELECT id, email, pass, name FROM members WHERE email =\'%s\' AND id = %d&quot;, $mysqli-&gt;real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email =\'x\\\' OR name LIKE \\\'%John%\' AND id = 2147483647\n</code></pre>\n'}, {'answer_id': 17305423, 'author': 'Deepak Thomas', 'author_id': 849829, 'author_profile': 'https://Stackoverflow.com/users/849829', 'pm_score': 7, 'selected': False, 'text': '<p>A simple way would be to use a PHP framework like <a href="http://en.wikipedia.org/wiki/Codeigniter#CodeIgniter" rel="noreferrer">CodeIgniter</a> or <a href="https://laravel.com/" rel="noreferrer">Laravel</a> which have inbuilt features like filtering and active-record so that you don\'t have to worry about these nuances.</p>\n'}, {'answer_id': 21179234, 'author': 'Rakesh Sharma', 'author_id': 878888, 'author_profile': 'https://Stackoverflow.com/users/878888', 'pm_score': 7, 'selected': False, 'text': '<blockquote>\n  <p><strong>Deprecated Warning:</strong>\n  This answer\'s sample code (like the question\'s sample code) uses PHP\'s <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n  \n  <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href="https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide" rel="noreferrer">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n\n<p>Using <a href="http://in3.php.net/pdo" rel="noreferrer">PDO</a> and <a href="http://in3.php.net/mysqli" rel="noreferrer">MYSQLi</a> is a good practice to prevent SQL injections, but if you really want to work with MySQL functions and queries, it would be better to use</p>\n\n<p><a href="http://php.net/manual/en/function.mysql-real-escape-string.php" rel="noreferrer">mysql_real_escape_string</a></p>\n\n<pre><code>$unsafe_variable = mysql_real_escape_string($_POST[\'user_input\']);\n</code></pre>\n\n<p>There are more abilities to prevent this: like identify - if the input is a string, number, char or array, there are so many inbuilt functions to detect this. Also, it would be better to use these functions to check input data.</p>\n\n<p><a href="http://in3.php.net/is_string" rel="noreferrer">is_string</a></p>\n\n<pre><code>$unsafe_variable = (is_string($_POST[\'user_input\']) ? $_POST[\'user_input\'] : \'\');\n</code></pre>\n\n<p><a href="http://in3.php.net/manual/en/function.is-numeric.php" rel="noreferrer">is_numeric</a></p>\n\n<pre><code>$unsafe_variable = (is_numeric($_POST[\'user_input\']) ? $_POST[\'user_input\'] : \'\');\n</code></pre>\n\n<p>And it is so much better to use those functions to check input data with <code>mysql_real_escape_string</code>.</p>\n'}, {'answer_id': 21449836, 'author': 'Chintan Gor', 'author_id': 2125924, 'author_profile': 'https://Stackoverflow.com/users/2125924', 'pm_score': 7, 'selected': False, 'text': "<p>There are so many answers for <strong>PHP and MySQL</strong>, but here is code for <strong>PHP and Oracle</strong> for preventing SQL injection as well as regular use of oci8 drivers:</p>\n\n<pre><code>$conn = oci_connect($username, $password, $connection_string);\n$stmt = oci_parse($conn, 'UPDATE table SET field = :xx WHERE ID = 123');\noci_bind_by_name($stmt, ':xx', $fieldval);\noci_execute($stmt);\n</code></pre>\n"}, {'answer_id': 21864784, 'author': 'Calmarius', 'author_id': 58805, 'author_profile': 'https://Stackoverflow.com/users/58805', 'pm_score': 6, 'selected': False, 'text': '<p>I\'ve written this little function several years ago:</p>\n\n<pre><code>function sqlvprintf($query, $args)\n{\n    global $DB_LINK;\n    $ctr = 0;\n    ensureConnection(); // Connect to database if not connected already.\n    $values = array();\n    foreach ($args as $value)\n    {\n        if (is_string($value))\n        {\n            $value = "\'" . mysqli_real_escape_string($DB_LINK, $value) . "\'";\n        }\n        else if (is_null($value))\n        {\n            $value = \'NULL\';\n        }\n        else if (!is_int($value) &amp;&amp; !is_float($value))\n        {\n            die(\'Only numeric, string, array and NULL arguments allowed in a query. Argument \'.($ctr+1).\' is not a basic type, it\\\'s type is \'. gettype($value). \'.\');\n        }\n        $values[] = $value;\n        $ctr++;\n    }\n    $query = preg_replace_callback(\n        \'/{(\\\\d+)}/\', \n        function($match) use ($values)\n        {\n            if (isset($values[$match[1]]))\n            {\n                return $values[$match[1]];\n            }\n            else\n            {\n                return $match[0];\n            }\n        },\n        $query\n    );\n    return $query;\n}\n\nfunction runEscapedQuery($preparedQuery /*, ...*/)\n{\n    $params = array_slice(func_get_args(), 1);\n    $results = runQuery(sqlvprintf($preparedQuery, $params)); // Run query and fetch results.   \n    return $results;\n}\n</code></pre>\n\n<p>This allows running statements in an one-liner C#-ish String.Format like:</p>\n\n<pre><code>runEscapedQuery("INSERT INTO Whatever (id, foo, bar) VALUES ({0}, {1}, {2})", $numericVar, $stringVar1, $stringVar2);\n</code></pre>\n\n<p>It escapes considering the variable type. If you try to parameterize table, column names, it would fail as it puts every string in quotes which is an invalid syntax.</p>\n\n<p>SECURITY UPDATE: The previous <code>str_replace</code> version allowed injections by adding {#} tokens into user data. This <code>preg_replace_callback</code> version doesn\'t cause problems if the replacement contains these tokens.</p>\n'}, {'answer_id': 22520937, 'author': 'Thomas Ahle', 'author_id': 205521, 'author_profile': 'https://Stackoverflow.com/users/205521', 'pm_score': 7, 'selected': False, 'text': '<p>A good idea is to use an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping" rel="noreferrer">object-relational mapper</a> like <a href="http://j4mie.github.io/idiormandparis/" rel="noreferrer">Idiorm</a>:</p>\n\n<pre><code>$user = ORM::for_table(\'user\')\n-&gt;where_equal(\'username\', \'j4mie\')\n-&gt;find_one();\n\n$user-&gt;first_name = \'Jamie\';\n$user-&gt;save();\n\n$tweets = ORM::for_table(\'tweet\')\n    -&gt;select(\'tweet.*\')\n    -&gt;join(\'user\', array(\n        \'user.id\', \'=\', \'tweet.user_id\'\n    ))\n    -&gt;where_equal(\'user.username\', \'j4mie\')\n    -&gt;find_many();\n\nforeach ($tweets as $tweet) {\n    echo $tweet-&gt;text;\n}\n</code></pre>\n\n<p>It not only saves you from SQL injections, but from syntax errors too! It also supports collections of models with method chaining to filter or apply actions to multiple results at once and multiple connections.</p>\n'}]
['https://Stackoverflow.com/questions/60174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/428190/']