开发者

How do i sanitize the query below?

can someone teach me how to sanitize the query ? Should i sanitize $first_word too ?

$question_text = sanitize($_POST['question_text']);

list($first_wo开发者_JAVA技巧rd) = explode(' ', $question_text);

$qStuff=mysql_query("SELECT c.field_name,t.category_name, d.domain_name FROM category_fields c, taxonomy_category t, taxonomy_domain d WHERE c.category_id = t.category_id AND t.domain_id = d.domain_id AND c.field_name = '$first_word'");


use PDO and parameter binding like this:

$sql = "INSERT INTO table (field) VALUES (?)";
$sth = $dbh->prepare($sql); 
$sth->execute(array($value));


If you want to keep using mysql_* function, you must use mysql_real_escape_string() to escape your string data :

$first_word_escaped = mysql_real_escape_string($first_word);
$qStuff=mysql_query("SELECT c.field_name,t.category_name, d.domain_name FROM category_fields c, taxonomy_category t, taxonomy_domain d 
     WHERE c.category_id = t.category_id 
           AND t.domain_id = d.domain_id 
           AND c.field_name = '$first_word_escaped'");


Note : as said in the Overview of the mysqli extension (quoting) :

What is PHP's MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database.
The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3.
This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

Note: If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.


Another solution would be to stop using the mysql_* familly of functions, and switch to eiter mysqli or PDO, using Prepared Statements -- which are one of the new features that are not supported by mysql_* :

  • mysqli::prepare,
  • PDO::prepare

With those, you would have to escape your data : it would be done automatically when binding their values.


"Sanitizing" is not necessarily the same as "SQL escaping". To SQL escape values for MySQL, use mysql_real_escape_string on the value you're going to put into the query:

$first_word = current(explode(' ', $_POST['question_text']));

// sanitize $first_word here if you want to to remove certain things

mysql_query("SELECT … '" . mysql_real_escape_string($first_word) . "'");


I suggest using a preg_match statement to limit character types. I also suggest using PHP PDO and prepared SQL statements. I'm on mobile or I would post links.


Use modern database functionality like PDO, and make use of paramterised queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜