致命错误:调用成员函数prepare() - 使用登录功能时

时间:2013-02-02 00:23:43

标签: php mysql pdo

不知道为什么我会一下子不断收到这些错误......

Fatal error: Call to a member function prepare() on a non-object in login.php on 
line 21 Call Stack: 0.0005 675088 1. {main}() login.php:0 0.0017 678544 2.
LoginSubmit() login.php:7

是因为我处理数据库连接的方式吗?顺便说一下,密码被存储为简单文本这一事实,因为正在构建的系统仅用于演示目的。

// database connection

$hostname = "xxx";
$username = "xxx";
$dbname = "xxx";
$password = "xxx";

try {
    $pdo = new PDO("mysql:host=$hostname;dbname=$dbname", 
    $username, $password);
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

// login code     

if(isset($_POST['pmsubmit']))
{
  LoginSubmit('pm', 'pmname', 'pmpass');
}

if(isset($_POST['tssubmit']))
{
  LoginSubmit('ts', 'dept', 'tspass');
}

function LoginSubmit($pm_or_ts, $the_name, $the_pass)
{
  $the_name = $the_name;
  $posted_name = $_POST[$posted_name];
  $posted_pass = $_POST[$posted_pass];
  // check if password matches the one in the table
  $query = $pdo->prepare("SELECT * FROM db_pass WHERE pass = :pass"); // line 21
  $query->execute(array(":pass" => $posted_pass));
  // if there is a match then we log in the user
  if ($query->rowCount() > 0)
  {
    // session stuff
    $_SESSION[$the_name] = $posted_name;
    // refresh page
    header( 'Location: ' . $pm_or_ts . '/index.php' ) ;
  } 
  // if there is no match then we present the user with an error
  else
  {
    echo "error";
    exit;
  }
}

1 个答案:

答案 0 :(得分:1)

您的$pdo变量在LoginSubmit函数中不可见,您应该看variable范围有问题..无论如何,您可以将变量添加到函数中,如下所示:

function LoginSubmit($pm_or_ts, $the_name, $the_pass)
{
    global $pdo;
    ..
    ..
}

或通过功能参数