在论坛上下文中的Mysqli_real_escape_string()或addslashes()

时间:2015-08-03 21:58:26

标签: php mysql select

我在php和MySql中创建了一个论坛,所以我需要插入并从我的数据库中选择数据。我使用mysqli连接到我的数据库。像这样:

$link=mysqli_connect("fake_server", "fake_user", "fake_pass", "fake_db");

$user=mysqli_real_escape_string($link, $_POST['user']);
$pass=hash("sha256", mysqli_real_escape_string($link, $_POST['pass']));

$combo=mysqli_fetch_array(mysqli_query($link, "SELECT 1 FROM users WHERE user='$user' AND pwd='$pass'"));
if($combo==0){
        // ERROR
} else {
        // CORRECT
}
mysqli_close($link);

问题是下一个问题: 每个人都说mysqli_real_escape_string()比插入的addslashes()好多了,但我希望用户可以在他们的主题中使用单引号和双引号。 Myqsli_real_escape_string()删除它们但addslashes()不会删除它们。在这种情况下我能做些什么?

2 个答案:

答案 0 :(得分:1)

您应该使用预先准备好的陈述http://php.net/manual/en/mysqli.quickstart.prepared-statements.php。将来请在您的问题中提供您的代码。以下是如何将您当前的代码用于预准备语句:

$link=mysqli_connect("fake_server", "fake_user", "fake_pass", "fake_db");
$user=$_POST['user'];
$pass=hash("sha256", $_POST['pass']); 
$stmt = $link->prepare("SELECT 1 FROM users WHERE user = ? AND pwd = ?");
$stmt->bind_param("ss", $user, $pass);
$combo=mysqli_fetch_array($stmt->execute());
if($combo==0){
        // ERROR
} else {
        // CORRECT
}
mysqli_close($link);

进一步阅读该主题:
How can I prevent SQL injection in PHP? {
{3}}
mysqli or PDO - what are the pros and cons? {
{3}}

答案 1 :(得分:0)

PDO使用参数化查询,忘记担心转义查询。

修改

您的测试代码:

$link=mysqli_connect("fake_server", "fake_user", "fake_pass", "fake_db");

$user=mysqli_real_escape_string($link, $_POST['user']);
$pass=hash("sha256", mysqli_real_escape_string($link, $_POST['pass']));

$combo=mysqli_fetch_array(mysqli_query($link, "SELECT 1 FROM users WHERE user='$user' AND pwd='$pass'"));
if($combo==0){
        // ERROR
} else {
        // CORRECT
}
mysqli_close($link);

PDO版本:

$pdo = new PDO('mysql:host=fake_server;dbname=fake_db', 'fake_user', 'fake_pass');

$query = $pdo->prepare("SELECT 1 FROM users WHERE user='?' AND pwd='?'");
$query->execute(array($_POST('user'), hash('sha256', $_POST('pass')));

if ($combo = $query->fetch ()) {
  // CORRECT
  // $combo would contain an array containing your select fields
} else {
  // ERROR
}