几天前我开始学习编码,我遇到了一些关于 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
这是我到目前为止的代码——这段代码在本地主机上工作,但是一旦我把它放到网上并导入数据库表,它给了我一些问题:
<?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
最佳答案
在连接到数据库后放置 mysql_real_escape_string()
将正常工作。
不过,你应该转向mysqli或PDO。 MySQL 现已弃用。 一些帮助您的链接
mysqli 和 PDO 中用于转义的等效命令分别是 mysqli_real_escape_string()
和 PDO::quote()
。
正如人们指出的那样,PDO 绝对是更好的选择。这是我之前写的比较 PDO 和其他答案的答案。
PDO - real facts and best practice?
这样做的另一个好处是,如果您使用带有命名参数的准备语句,则无需使用转义函数。
关于php - mysql_real_escape_string() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13070781/