Beginner Help: PHP MySQL (PDO) Function

I am trying to learn PHP and setup a user access based website. I finally found a template that is mostly simple to use and implement. However after hours of struggling to modify the template I have to kindly ask for assistance.

The following code works great and I have modified the original template to be able to login using the email address as username and the stored password from the database. The original template were based on a username login instead of using the email address. What I am trying to achieve now is to somehow also include the field "username" from the same database and table and store it as a $username parameter to use elsewhere on the site, for example with "echo". I would like to still use the field but for the name of the registered member, rather than a username for login.

I'm sure there is an easy way but whatever I change I keep getting error messages and I simply seem to not understand the syntax just yet.

<?php include('password.php'); class User extends Password{ private $_db; function __construct($db){ parent::__construct(); $this->_db = $db; } private function get_user_hash($email){ try { $stmt = $this->_db->prepare('SELECT password FROM members WHERE email = :email AND active="Yes"'); $stmt->execute(array('email' => $email)); $row = $stmt->fetch(); return $row['password']; } catch(PDOException $e) { echo '<p class="bg-danger">'.$e->getMessage().'</p>'; } } public function login($email,$password){ $hashed = $this->get_user_hash($email); 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; } } } ?>


you just need to extend your code slightly.

at the moment your query is only bringing out 1 field, the password.

SELECT * FROM members WHERE email = :email AND active="Yes"

this will then return the whole row, not just one field.

you can then extract the username and put it in a session variable like this:

$_SESSION['username'] = $row['username'];

which you can then use throughout the rest of the site. Make sure you have session_start(); at the beginning of all files that youd like to access the session vars. If you want to use other fields, then just change the parameter to 'firstName', or 'fullName' or whatever the fields are called.

as a bit extra, you could also extend your query to allow the user to log in with their email OR their username by adding this.

SELECT * FROM members WHERE (email = :email OR username = :email) AND active="Yes"

if you were going to do that, Id suggest changing the :email holder to something more sensible like :user so that it makes more sense to read the code.


your'e going to need to get your get_user_hash() function to return back $row in its entirety, and then add your session var from there. Its a bit back to front as this probably isn't the best login script I've ever seen.

in get_user_hash(), change

return $row['password'];


return $row;

and then in function login,

public function login($email,$password){
$row = $this->get_user_hash($email);
$hashed = $row['password'];

if($this->password_verify($password,$hashed) == 1){
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = true;
return true;

really, $hashed is nothing more than the users password which password_verify() uses to compare the encrypted password in the db.

Category:php Time:2019-01-10 Views:1
Tags: php mysql pdo

Related post

  • Datetime NOW PHP mysql (+ PDO variant) 2009-10-15

    Thanks for looking. All helpful answers/comments are up voted. In php, you can use NOW() like this: mysql_query("INSERT INTO tablename (id, value, time_created) VALUES ('{$id}', '{$value}', NOW())"); How can I do the same thing in PDO. When I bind li

  • mySQL table relations or just use one table?! Need Help php mysql 2010-10-14

    I'm trying to create a drop down select option using PHP, MySQL, and ajadx I have the PHP and ajax pretty much figured out but I'm stumped on how I should organize my tables I couldn't decide so I created it both ways: The first way the tables are: C

  • Php mysql LOWER function with AES_DECRYPT 2011-10-23

    I have AES encrypted data stored in the database using php mysql. Which I entered using AES_ENCRYPT. Problem is that data is coming from iphone and "first name" of member is coming with first letter in UPPER CASE and stored as Upper. For examle 'Pooj

  • SphinxQL with php mysqli/pdo and prepared statements 2011-11-06

    When querying Sphinx through SphinxQL would you gain the standard benefits of using mysqli/pdo in PHP? In additions is there any benefit to using prepared statements with SphinxQL? Are they even supported? --------------Solutions------------- I don't

  • Time-specific data - how to do with PHP/MySQL/PDO? 2012-01-01

    I've got a testing page for an internet radio station on localhost, and it's got this PHP file included in it: <?php /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password

  • PHP Mysql PDO number of bound variables does not match number of tokens 2012-02-17

    Hi i've looked around here but can't seem to find an answer too my problem. This is the first time i've used PDO and so am a complete newbie to it. I have a load of data split in to 2 tables and want to merge them into one, there are other ways of do

  • Is this PHP/MySQL delete function secure? 2011-05-21

    I have a setup where I am deleting entries from a table. It is based on the querystring of the URL which I'm thinking might be a bad way to start anyway. So if the URL is: And the php in delete.php

  • php-mysql alternative function of rollback 2012-03-15

    I have two tables as author and book. I want to insert data from author table to book table. If insert is successfully then the data of author table will be deleted , if not successes then data will not be deleted from author table. I want to use Rol

  • PHP MySQL login function 2011-02-09

    I'm using this: function authUser($username, $password){ connectDB(); $sql = "SELECT id, username FROM users where username = '".$username."' and password = '".$password."'"; $result = mysql_query($sql); $num_rows = mysql_num_rows($result); if ($num_

  • PHP MySQL PDO lastInsertID causes fatal error 2011-12-20

    I tried looking through some other posts, but didn't see anything exactly what I'm looking for. I have a DB query $sql = "INSERT INTO groups(Name) VALUES (:name)"; $dbs = $dbo->prepare($sql); $dbs->bindParam(":name", $_POST['name'], PDO::PARAM_

  • Optimize PHP Mysql Count Function 2012-01-24

    I count MySQL rows using this function: function sqlcount($table) { $sql = mysql_query("SELECT COUNT(0) FROM $table;"); $sql = mysql_fetch_array($sql); return $sql[0]; } Print the result: echo sqlcount("members"); But this does not work and does not

  • PHP MySQL date functions 2012-03-15

    I am working with dates, in both PHP as well as MySQL. EVerytime I use to convert date in unix format. But this time I have taken field in DB as date. But issue is it is taking yyyy-mm-dd format. I want to store it in dd-mm-yyyy format. Is this possi

  • PHP MySQL PDO -> ON INSERT if value already there do another query 2012-05-02

    I have a mysql db with two tables. The first table is called 'uniqueReferences' and the second one 'duplicatedReferences'. The two tables have two fields only: an id field (auto-incremented) and a field called Reference. What I would like is as follo

  • PHP mysql recursive function array_unshift 2013-08-26

    I have problem with recursive function in PHP. I call function and get row from database, than I put the row into array and I call function again to get other rows, who are conected with the row... Problem is, that array_unshift save only first row a

  • Php / MySQL search function: there must be an easier way of achieving this? 2010-08-17

    //lets get the auto name set $accepted = 0; $sql = mysql_query("SELECT * FROM ".TBL_FACTIONS." WHERE f_name='no_name'"); $numrows = mysql_num_rows($sql); //default name 1 if($numrows == 0){ $auto_name = 'no_name'; $accepted = 1;} //default name 2 if

  • How do I fix this weird PHP/MySQL issue caused by if statement? 2011-04-13

    I'm a beginner to PHP/mySql. I'm writing a CMS and still in the early stage. I wrote a code to take the information from the mySql table and but it into a HTML table. The problem is , before applying a certain IF statement , the whole data in the myS

  • Managing User Profiles with PHP/MySQL for Beginners 2010-03-28

    I am beginner in PHP/MySql and would develop a simple site that has user management. I like the idea of using OpenId's (like stackoverflow uses). I wonder from where to start? What should I read? I have not much time so probably will net enter in all

  • codeigniter 2 uses pdo or php mysql function for it's active record? 2011-04-16

    Does CodeIgniter 2 use PDO or PHP MySQL functions for its active record class? --------------Solutions------------- CI does not use PDO. PDO in Codeigniter - Protect vs SQL Injection CI uses mysql_real_escape_string() to help guard against injection

  • Beginner Help: Unable to get form variables working in PHP/HTML 2011-04-08

    I jut recently started learning PHP from a book called PHP/MySQL Programming for the Absolute Beginner by Andy Harris. In one of his samples, he writes that this code should function (I've cut it short a bit): <html> <head> <title>F

  • MySQL/PDO internal functioning 2011-08-24

    I search Internal functionning with mysql. I have already read some function in MySQL API for C, for example mysql_store_result and mysql_use_result, and i have done some tests for PHP memory usage with both PDO::MYSQL_ATTR_USE_BUFFERED_QUERY values,

Copyright (C), All Rights Reserved.

processed in 0.366 (s). 13 q(s)