MySQL/PHP: Allow special characters and avoid SQL injection

倾然丶 夕夏残阳落幕 提交于 2019-12-13 22:31:33

问题


How can I allow special characters like " ' \ / : ; etc without open up for SQL injection using the code below:

$opendb = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$text = $_POST['text'];

mysql_query("UPDATE table SET text='" . $text . "' WHERE 
id='" . $_GET['id'] . "'");

mysql_close($opendb);

$text contains a sentence from a HTML textarea. When I tries to enter text in a quote it just insert the text before the quotes.


回答1:


Prepared statement

This would be the safest way to go about doing this. Check out this link for more: How can I prevent SQL injection in PHP?

You might also need to turn off magic quotes, depending what PHP version you are running.

<?php

if( isset($_POST['text']) && isset($_GET['id']) && 
    is_int($_GET['id']) && $_GET['id']>0 ){

     $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

     /* check connection */
     if (mysqli_connect_errno()) {
         printf("Connect failed: %s\n", mysqli_connect_error());
         exit();
     }

     $query = 'UPDATE table SET text = ? WHERE id = ?';

     /* prepare your statement safely */
     $stmt = $mysqli->prepare($query);

     /* bindes variables after statement is prepared */
     $stmt->bind_param('si', $_POST['text'], $_GET['id']);

     /* execute prepared statement */
     $stmt->execute();

     /* close statement */
     $stmt->close();

     /* close connection */
     $mysqli->close();
}else
     echo 'Error: ID and/or Text are invalid';
?>



回答2:


Well, maybe the simplest solution is to use mysql_real_escape_string() function like this:

$opendb = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$text = $_POST['text'];

mysql_query("UPDATE table SET text='" . mysql_real_escape_string($text) . "' WHERE 
id='" . $_GET['id'] . "'");

mysql_close($opendb);

Edit: using this code you could allow special characters in $text variable to be saved into the database.

You should escape $_GET['id'] also.



来源:https://stackoverflow.com/questions/18763609/mysql-php-allow-special-characters-and-avoid-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!