Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Its always a bad idea to put data from a get request directly into SQL, and there are many easy ways to prevent SQL injection.</p> <p>For the simple case where you know you want a numeric ID, then you can simply force the value to be numeric and then there is no chance of SQL injection. One way might be okoman's usage of <code>sprintf()</code>, maybe something like this:</p> <pre><code>$sql = "INSERT INTO table VALUES(".sprintf("%d",$_GET['id']) .")"; </code></pre> <p>though I think its ugly and bad form. Something like this is nicer:</p> <pre><code>$sql = "INSERT INTO table VALUES(".(int)$_GET['id']) .")"; </code></pre> <p>Which simply casts the value to an int - if its not a number that can be cast to int - you'll get a "0" which may or may not be what you want.</p> <p>Other alternatives (and for when your data is not supposed to be a number) include using escaping functions such as <code>add_slashes()</code> or the above mentioned <code>mysql_real_escape_string()</code>.</p> <p>IMHO, the best way to use database access from within PHP and very easily protect from SQL injection is to use the new PHP PDO library ( <a href="http://php.net/PDO" rel="nofollow noreferrer">http://php.net/PDO</a> ). This allows you to write SQL strings that contain no data whatsoever, and have the data added later inside the database server itself. In this form there is absolutely no way to do SQL injection.</p> <p>Here is some example code:</p> <pre><code>$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); $stmt = $dbh-&gt;prepare("INSERT INTO table VALUES (?)"); $stmt-&gt;bindParam(1, $_GET['id']); $stml-&gt;execute(); </code></pre> <p>As you can see, the data is not added to the SQL query itself and so no need for escaping.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload