PHP PDO将名称声明为变量

时间:2014-05-07 05:05:00

标签: php variables pdo

所以在我的项目中,我试图声明一个变量,这样如果登录就会显示它们的全名。我假设这是一个从表中获取数据的查询,但我&#39 ;我不确定如何确保它获得某个用户的名字而不是桌面上的名字

这是我的注册码。

if( $user->is_logged_in() ){ header('Location: index.php'); } 

//如果表单已提交处理它 如果(isset($ _ POST ['提交'])){

//very basic validation
if(strlen($_POST['username']) < 3){
    $error[] = 'Username is too short.';
} else {
    $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
    $stmt->execute(array(':username' => $_POST['username']));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!empty($row['username'])){
        $error[] = 'Username provided is already in use.';
    }

}

if(strlen($_POST['password']) < 3){
    $error[] = 'Password is too short.';
}

if(strlen($_POST['passwordConfirm']) < 3){
    $error[] = 'Confirm password is too short.';
}

if($_POST['password'] != $_POST['passwordConfirm']){
    $error[] = 'Passwords do not match.';
}

//email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    $error[] = 'Please enter a valid email address';
} else {
    $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
    $stmt->execute(array(':email' => $_POST['email']));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!empty($row['email'])){
        $error[] = 'Email provided is already in use.';
    }

}
    //email validation
if(strlen($_POST['fullname']) < 2){
    $error[] = 'Please enter a valid full name';
} else {
    $stmt = $db->prepare('SELECT fullname FROM members WHERE fullname = :fullname');
    $stmt->execute(array(':fullname' => $_POST['fullname']));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!empty($row['email'])){
        $error[] = 'Email provided is already in use.';
    }

}

//if no errors have been created carry on
if(!isset($error)){

    //hash the password
    $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

    //create the activasion code
    $activasion = md5(uniqid(rand(),true));

    try {

        //insert into database with a prepared statement
        $stmt = $db->prepare('INSERT INTO members (username,password,email,fullname,active) VALUES (:username, :password, :email, :fullname, :active)');
        $stmt->execute(array(
            ':username' => $_POST['username'],
            ':password' => $hashedpassword,
            ':email' => $_POST['email'],
            ':fullname' => $_POST['fullname'],
            ':active' => $activasion
        ));
        $id = $db->lastInsertId('memberID');

        //send email
        $to = $_POST['email'];
        $subject = "Registration Confirmation";
        $body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n Regards Site Admin \n\n";
        $additionalheaders = "From: <".SITEEMAIL.">\r\n";
        $additionalheaders .= "Reply-To: $".SITEEMAIL."";
        mail($to, $subject, $body, $additionalheaders);

        //redirect to index page
        header('Location: index.php?action=joined');
        exit;

    //else catch the exception and show the error.
    } catch(PDOException $e) {
        $error[] = $e->getMessage();
    }

}

}

更新了用户类:

<?php

包括(&#39; password.php&#39); class用户扩展密码{

private $_db;

function __construct($db){
    parent::__construct();

    $this->_db = $db;
}

private function get_user_hash($username){  

    try {
        $stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username');
        $stmt->execute(array('username' => $username));

        $row = $stmt->fetch();
        return $row['password'];

    } catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    }
}

public function login($username,$password){

    $hashed = $this->get_user_hash($username);

    if($this->password_verify($password,$hashed) == 1){

        $_SESSION['loggedin'] = true;
        return true;
    }   
}

public function logout(){
    session_destroy();
}

public function is_logged_in(){
    if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
        return true;
    }

}

}

3 个答案:

答案 0 :(得分:0)

在您的登录方法中,将$username保存为$_SESSION['loggedin']下的会话值,您可以稍后检索这个值...

public function login($username,$password){

    $hashed = $this->get_user_hash($username);

    if($this->password_verify($password,$hashed) == 1){

        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username;
        return true;
    }   
}

然后在文件底部有另一种方法,就像......

public function get_username(){
    if(isset($_SESSION['username'])){
       return $_SESSION['username'];
    }
}

然后您可以像$ user-&gt; get_username()一样调用此方法来获取当前登录用户的用户名。然后从数据库中获取他们的全名需要使用&#34; WHERE username =:username&#34;进行简单查询。我可以添加这样的另一种方法来使事情变得更容易......

 public function get_fullname(){
    if(issset($_SESSION['username']){
        $stmt = $this->_db->prepare('SELECT fullname FROM members WHERE username = :username');
        $stmt->execute(array('username' => $this->get_fullname()));

        $row = $stmt->fetch();
        return $row['fullname'];
    }
}

答案 1 :(得分:0)

为什么不简单地从数据库中选择它们?

如果我混入一些伪代码,请不要介意我,因为我对你的变量不是很熟悉。

首先,如果登录凭据正确,则创建/启动SESSION。

if($login_credentials_correct){ //lol you know what I mean here
  session_start();
  $_SESSION['username'] = $_POST['username']; // or wherever it may have come from
}

现在会话已启用,您可以执行与此

类似的查询
<?php

  session_start(); // fixed

  $username = $_SESSION['username'];

  $stmt = $db->prepare('SELECT fullname FROM members where username= :username');

  $stmt->execute(array(':username'=>$username));
  $row = $stmt->fetch(PDO::FETCH_ASSOC);

  $fullName = $row['fullName']; //I am not sure if this is the correct index.
  //to make sure, use var_dump($row) and find out which index has the full name
  echo $fullName; //voila.
?>

现在,只有当您的用户名是唯一的时,此代码才有效。大声笑。哪个网站没有唯一的用户名。

答案 2 :(得分:0)

你可以发布你的登录代码吗?到目前为止,我会尽力回答你的问题。 如果您希望用户能够登录并使其数据可用于显示,请执行此操作

  if(!($_SERVER['REQUEST_METHOD'] == "POST")){
     //Code here for users trying to access page incorrectly
  }else{

     if(isset($_POST['username']) && ($_POST['username'] <= $UsernameMaxLength)){
       $username=strip_tags(stripslashes($_POST['username'])); //Clean the data up
     }else{
       //Error handling code
     }

     if(isset($_POST['password']) && ($_POST['password'] <= $PasswordMaxLength)){
       //I would advise you use SHA1() instead for password encryption, but I'll use what you used here
       $password=$user->password_hash(strip_tags(stripslashes($_POST['password'])), PASSWORD_BCRYPT); //Clean the data up
     }else{
       //Error handling code
     }

     if(!isset($username) || !isset($password)){
        //Error handling code
     }else{
         $stmt = $db->prepare('SELECT fullname FROM members where username= :username and password=:password');

         $stmt->execute(array('username':$username,'password':$password));
         $row = $stmt->fetch(PDO::FETCH_ASSOC);
         //Code here to make sure there is a row with the number given and all that 
         //other jazz. In this code I'll assume all went well
         if(All_went_well){
            //Start your session to store variables you want
            session_start();
            $_SESSION['fullname']=$row['fullname'];
          }

     }

  }