php - mysql_real_escape_string() 问题

标签 php mysql string escaping

几天前我开始学习编码,我遇到了一些关于 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 现已弃用。 一些帮助您的链接

  1. Moving from mysql to mysqli or pdo?
  2. mysqli or PDO - what are the pros and cons?

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/

相关文章:

php - 如何在运行时更改应用环境?

PHP 错误日志已成功发送到 Sentry,但在 Sentry 仪表板上没有显示日志

mysql - SQL 按月份名称按时间顺序而不是按字母顺序排序

c++ - 解析逗号分隔的 std::string

java - Java 中有等效的 strpbrk 吗?以及如何使用它?

php - 使用 PHP Carbon,以秒为单位删除两个时间段重叠的时间

php - 使用 MySQL 查询在 PHP 中计算时间

php - 在 MySQL 服务器之间移动数据时避免自动递增 ID 冲突

php - 创建一个触发器,一旦到达设定日期就会清除条目

ios - 从网页 iOS 中的文本字段获取字符串