1

几天前我开始学习编码,我遇到了 mysql_real_escape_string 的一些问题,特别是 login.php。

错误消息:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'elegant'@'localhost' (using password: NO) in /home/elegant/public_html/php/login.php on line 3

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the     server could not be established in /home/elegant/public_html/php/login.php on line 3

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'elegant'@'localhost' (using password: NO) in /home/elegant/public_html/php/login.php on line 4

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/elegant/public_html/php/login.php on line 4
Please enter a username and a password

这是我到目前为止的代码——这段代码在 localhost 中工作,但是一旦我把它放到网上并导入数据库表,它给了我一些问题:

<?php

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

if ($username&&$password)

{

$connect = mysql_connect("localhost","elegant_root","password;1") or die("Couldn't             connect!");
mysql_select_db("elegant_ezworkstation") or die("Couldn't find database");

$query = mysql_query("SELECT * FROM users WHERE username=$username");

$numrows = mysql_numrows($query);

if ($numrows!=0)
{

while ($row = mysql_fetch_assoc($query))
{

    $dbusername = $row['username'];
    $dbpassword = $row['password'];

}

if ($username==$dbusername&&$password==$dbpassword)
{

    echo "You're in";

}
else
    echo "Incorrect password!";

}
else
die("That user doesn't exist");

}

else
die("Please enter a username and a password");

?>

编辑:我更改为 mysqli,但出现以下错误:

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/elegant/public_html/php/login.php on line 3

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home/elegant/public_html/php/login.php on line 4
4

1 回答 1

5

mysql_real_escape_string()连接到数据库后放置将正常工作。

但是,您应该转向 mysqli 或 PDO。MySQL 现在已弃用。几个链接可以帮助你

  1. 从 mysql 迁移到 mysqli 或 pdo?
  2. mysqli 或 PDO - 有什么优点和缺点?

mysqli 和 PDO 中用于转义的等效命令分别是mysqli_real_escape_string()PDO::quote()

正如人们所指出的,PDO 绝对是更好的选择。这是我之前写的将 PDO 与其他人进行比较的答案。

PDO - 真实的事实和最佳实践?

这样做的另一个好处是,如果您使用带有命名参数的准备好的语句,则不需要使用转义函数。

于 2012-10-25T14:30:33.110 回答