【发布时间】:2012-10-25 14:25:32
【问题描述】:
几天前我开始学习编码,我遇到了 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
【问题讨论】:
-
在调用
mysql_real_escape_string之前需要mysql connection... 放在连接后mysql_connect -
重写你的代码并使用
mysqli_() -
如果您正在学习编码,请不要从任何使用 mysql 的教程中学习......寻找使用 mysqli 或(更好)PDO 的教程
-
我想知道您使用的什么资源让您在 2012 年走上了使用
mysql_query的道路。 -
请不要使用
mysql_*函数编写新代码。它们不再维护,社区已经开始deprecation process。看到 red box 了吗?相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is good tutorial