首页 > 解决方案 > 登录系统在 pdo php 中无法正常工作

问题描述

这是我的注册表单,它可以正常工作并将我发送到索引文件,但是当我将它与登录结合使用时,它给了我一个错误

<?php
session_start();

$username="";
$email="";
$password="";
$errors=array();
$success=array();
try{
    $host='localhost';
    $user='root';
    $password='';
    $dbname='login';

//Set dsn
$dsn='mysql:host='.$host.';dbname='.$dbname;

$pdo=new PDO($dsn,$user,$password);

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);


}catch(Exception $e){

echo "error".$e->getMessage();
}



if(isset($_POST['register'])){


  $email=trim($_POST['email']);
  $password=trim($_POST['password']);
  $password_2=trim($_POST['password_2']);

  if(empty($email)){
    array_push($errors,'Email SHOULd be filled ');
  }
  if(empty($password)){
    array_push($errors,'Password should be filled ');
  }
  if($password !=$password_2){
    array_push($errors,"Passwords do not match");

  }

  if(count($errors)==0){
  $password_hash=md5($password);
  $insert=$pdo->prepare("INSERT INTO users (email,password) VALUES (:email,:password)");
  $insert->bindParam(':email',$email);
  $insert->bindParam(':password',$password);
  $insert->execute();
  $_SESSION['email']=$email;
  $_SESSION['success']='You have registered ';
  header('Location:index.php');
  }


}

这是我的登录表单,它不起作用我的代码有一些问题。

首先我不知道我的登录页面的列名是否应该与注册列名匹配

if(isset($_POST['login'])){
  $email=trim($_POST['email']);
  $password=trim($_POST['password']);

  if(empty($email)){
  array_push($errors,'Email should be filled ');
  }
  if(empty($password)){
    array_push($errors,'Password should be filled );
  }

  if(count($errors)==0){
      $select=$con->prepare("SELECT * FROM   users WHERE email='$email' and password='$password'");
      $select->execute();
      $count=$query->fetchColumn();
      echo '111';
    //  if($c11ount=="1"){
      //    header('Location:index.php');
    //  }


  }

}

这只是一个注销系统

if(isset($_GET['logout'])){
    session_destroy();
    header('location:login.php');
}

?>
  <link rel="stylesheet" href="inde.css">

    enter code here

标签: phpdatabaseloginbackendregistration

解决方案


我在您的脚本行中发现了一些错误

  • array_push($errors,'需要填写密码);

将 $conn 作为数据库连接并将登录代码替换为:

<?php
    if(isset($_POST['login'])){
      $email=trim($_POST['email']);
      $password=trim($_POST['password']);

      if(empty($email)){
      array_push($errors,'Email should be filled ');
      }
      if(empty($password)){
        array_push($errors,'Password should be filled' );
      }
    //database connection is $conn
      if(count($errors)==0){
          $select=$conn->prepare("SELECT * FROM users WHERE email='$email' and password='$password'");
          $select->execute();
          $count=count($select->fetch(PDO::FETCH_ASSOC));//fetch array and count it
      if($count=='1'){
          header('Location:index.php');
     }
      }
?>

推荐阅读