我几天前开始学习编码,我遇到了一些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
答案 0 :(得分:5)
连接到数据库后放置mysql_real_escape_string()
可以正常工作。
但是,你应该转向mysqli或PDO。 MySQL现已弃用。 一些帮助你的链接
mysqli和PDO中用于转义的等效命令分别为mysqli_real_escape_string()
和PDO::quote()
。
正如人们所指出的那样,PDO绝对是更好的选择。以下是我之前将PDO与其他人进行比较的答案。
PDO - real facts and best practice?
另一个优点是,如果您使用带有命名参数的预准备语句,则不需要使用转义函数。