Hello I am posting maybe 4th question about this issue but nobody can help me so far, so let's start from the begining, what I need is simple I need to: Set userID variable from column name "userID' inside table named "users" into the Sessions array: $_SESSION['userID']
here is my login page code:
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
and here is my user class which operates the function login:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
The code is working fine I just want to add addition to it which will get the userID value from the column of the users table inside the database ans store it to the $_SESSION['userID'] after user is loged in.
So any idea how to reach this goal in my code ? thanks!
If you just want the UserID from the table, you're going to have to do a $stmt->fetch() to load it first, then you can store it in your SESSION.
So after the execute in function userLogin() do:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
If the user was found $result will then contain all of the fields from the users table. So:
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
Related
I've been trying to get logged persons user_id which is in user_login table in my database and insert it to the another table.
What I know is, get the user_id from the user_login using query and assign that query to the SESSION variable and put that variable in another query where I want to insert it in the table but I'm unable to write a perfect code for it.The only thing I'm achieving is it taking the user_id as 1 in the new table.It would be a great help if you can review my code correct it.
<?php
ob_start();
include ('header.php');
require('includes/connect.php');
require('includes/product.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['add'])){
if (isset($_SESSION['logged_in'])) {
$query = $pdo->prepare("SELECT user_id FROM user_login ");
$user_id=$query->execute();
$_SESSION['user_id']['id']=$user_id;
$query = $pdo -> prepare("INSERT INTO cart_items(product_id , user_id, Price) VALUES (?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['user_id']['id']);
$query -> bindValue(3, $data['new_price']);
$query ->execute();
header('location:cart.php');
}
else{
header('location:Login Page.php');
}
}
?>
This is where I have done the user validation while logging in (connect.php)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "ecom";
try{
$pdo = new PDO('mysql:host=localhost;dbname=ecom','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
exit('Database error.');
}
function login(){
global $pdo;
$username = $_POST['email'];
$password = md5($_POST['password']);
if(empty($username) or empty($password))
{
$error = "Please fill all the fields";
}
else
{
$query = $pdo->prepare("SELECT * FROM user_login WHERE name = ? AND password = ? ");
$query->bindValue ( 1, $username);
$query->bindValue ( 2, $password);
$query->execute();
$num=$query->rowCount();
if($num==1) {
$_SESSION['logged_in']= true;
//header('location :' .$_SESSION['redirectURL']);
header('location: index.php');
exit();
}
else{
$error = "Please enter correct Username and Password";
}
}
}
?>
Thank you in advance.
replace your else part with this code
$query = $pdo->prepare("SELECT * FROM user_login WHERE name = ? AND password = ? ");
$query->bindValue ( 1, $username);
$query->bindValue ( 2, $password);
$query->execute();
$data = $query->fetchAll(PDO::FETCH_ASSOC);
$num=$query->rowCount();
if($num==1) {
$_SESSION['logged_in']= true;
$_SESSION['user_id'] = $data[0]["user_id"];
//header('location :' .$_SESSION['redirectURL']);
header('location: index.php');
exit();
} else{
$error = "Please enter correct Username and Password";
}
then you can get user id from session
class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( >$data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( >$data['password'] ) );
}
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
I would like to check if a user already exist in my database, because it lets me create accounts with same username anytime.
Thanks.
I would recommend a few things to help here.
1) Make your username column unique in the database. This would prevent usernames that are not unique from being inserted.
2) Once you have a unique index on username, attempt the insert, and check for success on the insert. Since you can get the error code from mysql, if the query was not successful and the error code is due to a duplicate value...throw the username already exists error.
This is the basic idea of how to return if the username exists.
public function username($username)
{
$sth = $this->db->prepare("SELECT id, username FROM table WHERE username = ?");
$sth->execute(array($username));
$row = $sth->fetch();
if(username == $row['username'])
{
do code here since username does not exist
} else {
echo 'username already exists';
}
}
$sell= mysql_query("select * from `signup` where emailid='$email'");
$cntc=mysql_num_rows($sell);
if($cntc==0) {
$sql=mysql_query("INSERT INTO `signup`(`firstname`,`lastname`,`emailid`,`dob`,`companyname`,`phoneno`,`password`) VALUES ('$name','$lastname','$email','$dob','$comname','$phone','$pass')");
if($sql) {
echo'inserted successfully';
}
} else {
echo'Email is already exist. ';
}
Hello I have 2 tables in my database one for courses and one for users, each of them has an id column.
I am trying to create a relationship between them, one user subscribe to one course. The result I am trying to store inside a 3rd table called subscription, which has a column for the course ID and column for user id.
The users are registering after passing log-in which is connected with a new session. After user click subscribe link which is
<a href='subscribe.php?id=".$row['id']."'>subscribe!</a>
they are taken to the backend php page where it is the inserted into database information:
<?php
session_start();
?>
$userid = $_SESSION['userID'];
$cursoid = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid ')")
or die(mysql_error());
at this point I have obtained the id of the course and it is inserted inside it, the problem is for the user ID I am not getting anything. How I can get the id for the current logged in user ?
here is the code of my class for the login function:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userID'] = $user->user_id;}
}
}
and finally here is the code of the login function:
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['id'] = $_POST['id'];
You should NOT be using sessionIds as userIds, instead you should be using the primary key of the user table after you have inserted the user row. Also, probably being pedantic, but you should rename your user variable to $user, $usr makes me wince.
Another way to get session id is: session_id
-- Edit --
public function userLogin() {
....
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userId'] = $user->user_id;
}
}
// We sessionized user id after validation, so we now have access to it
$userid = $_SESSION['userId'];
// Using straight mysql api is frowned upon, this should be converted to PDO before production use
mysql_query("INSERT INTO `subscriptions` (curso_id, user_id) VALUES ('$cursoid', '$userid ')")
or die(mysql_error());
Every time you want to work with a session, you must call session_start function at the beginning of the file. You called it in login function, but don't call in subscribe.php. Try this:
session_start();
$userid = $_SESSION['id'];
$cursoid = $_GET['id'];
//rest of the code
Also you have a minor error here as well, you had a space in this line VALUES ('$cursoid', '$userid ')")
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid')")
or die(mysql_error());
Hi I am trying to get value from userID column in my table inside the sessein array.
in my register class I have the following code:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
$_SESSION['userID'] = $user->user_id;
}
for which syntaxis I am not very sure that it will sessionize the UserID value of the logged user.
and in the login where the array is created I have
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['userID'] = $_POST['userID'];
but it gives me every time NULL result how to fix it ?
first of all if you're posting the form you should use $_POST['userID'] and first check it if you retrieving the value in your $_POST['userID'] then you have to start session like this
session_start();
$_SESSION['userID'] = $_POST['userID']
but the first one code i understand you're using codeigniter or OOP $user->user_id the first $user is your variable and second one is user_id which may be your access modifier also check $user->user_id it has value then do same
session_start();
$_SESSION['userID'] = $user->user_id;
I'm in the process of learning PHP and MySQL.
I would like from the script to recognize a specific name and redirect it to admin.php. For example "if Username is Brian redirect him to admin.php, if the username is everything except Brian, redirect him to account.php".
Both Brian and the other persons must be registered in the database to be able to login. I thought on redirect based on MySQL user id, but I don't know how to write the code. Or if you know another simple solution.
Here is the script:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT userID FROM users WHERE username='username' AND password= :password AND userTypeId = 1 LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
And this is the script from index.php (where the user writes his name and password)
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome";
} else {
echo "Incorrect Username/Password";
}
}
?>
Rather than recognizing a name (which you would have to parse) I believe it would be more efficient (and easier to implement) if you instead direct by user number (or whatever you're calling your primary key).
So if your user name is "Brian" and is the first user, with user number 1 then point to your table where the 1 is located, assuming it's stored as the integer 1 and not the string "1" instead.
Computers generally have an easier time dealing with integers rather than arrays. You can do it by string, but it's always going to be more work for you and the machine.
As far as redirecting goes, upon logging in, just do a check:
if user number is equal to [Brian's user number] then redirect to admin.php
else redirect to account.php
(Also you'll want to make sure that admin.php requires Brian be the logged in user, or anybody else could just navigate there manually)
The method $user->userLogin should return the id of current login user when successful login and return FALSE when failure login . then redirect to a admin.php or or account.php depend the returned id
First, try to fetch username and correct binding name for username:
$sql = "SELECT username FROM users WHERE username = :username AND ...
instead of:
$sql = "SELECT userID FROM users WHERE username='username' AND ...
//^ //^
Also just return fetched username on successful status. It returns a single column from the next row of a result set or FALSE if there are no more rows.
return $stmt->fetchColumn();
And then check logged in username by if condition to redirect desired page:
$usr = new Users;
$usr->storeFormValues( $_POST );
$username = $usr->userLogin();
if( $username !== false ) {
if(strtolower($username) == "brian"){
header("Location: admin.php");
} else {
header("Location: account.php");
}
} else {
echo "Incorrect Username/Password";
}