PHP在准备SQL语句时抛出致命错误

PHP在准备SQL语句时抛出致命错误,php,pdo,Php,Pdo,在我的PHP应用程序中,我希望用户能够使用数据库中记录的电子邮件、用户名和号码登录。然而,我 init.php <?php $server = 'localhost'; $username = 'default'; $password = 'xxxx'; $database = 'default'; try{ $conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password); } catch(

在我的PHP应用程序中,我希望用户能够使用数据库中记录的电子邮件、用户名和号码登录。然而,我

init.php

<?php
$server = 'localhost';
$username = 'default';
$password = 'xxxx';
$database = 'default';

try{
   $conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
   die( "Connection failed: " . $e->getMessage());
}
<?php
session_start();
if(isset($_SESSION['user_name'])!='') {
header('Location: index.php');
}
include_once 'init.php';
//check if form is submitted
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$records = $conn->prepare('SELECT username,email,number,password FROM users WHERE username = :login OR email = :login OR number = :login');
$records->bindParam(':login', $email);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);

$message = '';

if(count($results) > 0 && password_verify($password, $results['password']) ){

$gome = $results['username'];$_SESSION['user_name'] = $gome;
$CookieExpire = 1000;
$time = 100 * 70 * 48 * 86400;
$time = time() + $time;
setcookie('username', '$gome', '$time');
setcookie('password', '$password', '$time');header("Location: /");

} else {
$message = 'Sorry, those credentials do not match';
}

}

?>
试试这个代码


这是变量的范围

try{
   $conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
   die( "Connection failed: " . $e->getMessage());
}
应该是

$conn = null;    
try{
   $conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
   die( "Connection failed: " . $e->getMessage());
}
您的$conn在try块内声明,因此它在外部不可见。通过在外部初始化,它将随处可见。

1)尝试将您的init.php代码移动到login.php,以确保按预期加载

2) 尝试在“new PDO..”之前声明全局变量$conn(全局$conn;),以检查这是否是范围问题


3) 如果前两个步骤没有说明问题,请检查是否加载了pdo(您可以使用中列出的函数进行检查)

旁注:您应该学会缩进代码。现在,它是难以辨认的…它可能是一些错误的选择。但只有您知道,$conn不能声明吗?我尝试了您的代码,但仍然无法解决它是否意味着无法解决此错误?或者还有其他方法吗?下面@m-stange的建议也可以,因为你没有定义任何函数。好吧,假设是你对他的答案投了赞成票,那么你能帮助他吗?或者你只是掌握了你的反对票经验?如果你不懂语言,请不要回答。你说的完全是胡说八道。我确实懂这门语言。虽然这是最简单的解决方案,但肯定不是最好的。它直接回答了他关于错误的问题,而不是关于他对其余代码做了什么。try-catch中的任何变量声明都可以在其外部看到。您的权利夏洛特,对此我深表歉意。我习惯于使用块作用域,即使在不使用块作用域的情况下,我也会在使用不使用块作用域的语言时忘记很多次。
$conn = null;    
try{
   $conn = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
} catch(PDOException $e){
   die( "Connection failed: " . $e->getMessage());
}