【问题标题】:PHP seems to be refusing to connect to MySQLPHP 似乎拒绝连接到 MySQL
【发布时间】:2011-12-10 22:15:11
【问题描述】:
<?php

function redirect_to_index_with_error(){
    echo '<meta http-equiv="refresh" content="0;url=index.php">';
}

function go_to_home(){
    echo '<meta http-equiv="refresh" content="0;url=home.php">';
}

$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";

mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing

mysql_select_db("mcp") or die(mysql_error());

$results = mysql_query($query) or die(mysql_error());

if(mysql_num_rows($results) == 0){
    redirect_to_index_with_error();
    exit();
}

$userID = null;
$name = null;
$school = null;
$mod = null;

while($user = mysql_fetch_array($results)){
    $userID = $user['ID'];
    $name = $user['Name'];
    $school = $user['School'];
    if($user['Mod'] == '1')
        $mod = true;
    else
        $mod = false;

}
if(!isset($_SESSION))
    session_start();

//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;

go_to_home();
exit();
?>

PHP 回显所有内容,直到“连接”为止。它甚至没有显示mysql错误。我已经让这段代码在带有 WAMP 的 Windows 上完美运行,但在带有 MAMP 的 Mac 上却没有。我已经验证服务器正在运行,所以我无法判断问题所在。我正在使用 PHP 5.3.6。

【问题讨论】:

  • 如果一切顺利,它似乎不会输出任何东西,是吗?
  • 对不起,我忘了发布整个代码。我现在就去做。
  • 这段代码在“连接”后应该回显什么?
  • 您是否验证并确保您要查找的用户确实存在?
  • 是的,我检查了 phpMyAdmin。 shane 的回答解决了这个问题。

标签: php mysql wamp mamp


【解决方案1】:

您需要在拨打mysql_real_escape_string()之前建立连接

所以将mysql_connect("localhost","root","") or die(mysql_error());移到顶部。

【讨论】:

    【解决方案2】:

    mysql_connect() 语句移至其他所有内容之上。

    // put this at the TOP
    mysql_connect("localhost:3306","root","") or die(mysql_error());
    

    【讨论】:

      【解决方案3】:

      正如其他人所提到的,请参阅以下说明: http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes

      此外,您至少应该在开发中看到错误。 见:error_reporting()

      【讨论】:

      • 不仅在开发中。 error_reporting 应始终为最大值
      • 对,我的意思是,在现场,错误输出应该发送到日志文件而不是在开发时显示在屏幕上,输出最容易查看时显示在屏幕上(除非您有一个运行 tail -f /path/to/log 的终端:))
      【解决方案4】:

      你必须在连接后调用 mysql_real_escape_string()。
      否则此函数将返回一个空字符串,您的查询将失败。

      虽然它会引发错误,但您似乎还没有看到。
      因此,您应该打开显示错误或查看错误日志 - 如果不能查看错误消息,就无法进行编程

      另外,你必须改进你的形式逻辑。
      要做出像“PHP 似乎拒绝连接到 MySQL”这样的声明,你必须先验证它。 Connect 只是一行并返回一个值。
      你可以验证这个值并做出一定的结论。
      但是运行几十行的整个代码并只针对其中一行进行陈述是没有意义的。

      【讨论】:

        猜你喜欢
        • 2018-06-08
        • 2018-05-19
        • 2023-02-03
        • 2013-01-05
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多