Reputation: 71
I am trying to failing to figure out how to add my user_id from my database to a session like my username is. I would like it so when I log in I can called the session to call the user id posts based on the username used to log in.
How do I do this?
my login php:
<?php
session_start();
$connect = mysql_connect( "localhost", "user", "pass") or die('Database could not connect');
$select = mysql_select_db( "database", $connect) or die('Database could not select');
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
chckusername($username, $password);
}
function chckusername($username, $password){
$check = "SELECT * FROM users WHERE username='$username'";
$check_q = mysql_query($check) or die("<div class='loginmsg'>Error on checking Username<div>");
if (mysql_num_rows($check_q) == 1) {
chcklogin($username, $password);
}
else{
echo "<div id='loginmsg'>Wrong Username</div>";
}
}
function chcklogin($username, $password){
$login = "SELECT * FROM users WHERE username='$username' and password='$password' ";
$login_q = mysql_query($login) or die('Error on checking Username and Password');
print_r($lohin_q);
if (mysql_num_rows($login_q) == 1){
header('Location: http://ct6014-williams.studentsites.glos.ac.uk/pages-multi-page/home.php');
$_SESSION['username'] = $username;
$_SESSION['user_id'] = $userid; //this is where I want to store the user id
}
else {
echo "<div id='loginmsg'>Wrong Password </div>";
}
}
?>
on home.php:
<?php echo "Your username is " . $_SESSION["username"] . "."; ?>
<?php echo "Your id is " . $_SESSION["user_id"] . "."; ?>
database names:
user_id
, username
, user_first_name
, user_last_name
, user_email
, password
, user_reg_date
EDIT:
Ahh, I forgot to say, I have used include( 'login.php' ); which created the session when I logged in as a user. The first username session echos but I cannot seem to figure out hoe to set up the user_id session
Upvotes: 0
Views: 510
Reputation: 16963
In chcklogin()
function, use mysql_fetch_array()
function to fetch the row from the result set and assign the required user data to $_SESSION
. So change your if (mysql_num_rows($login_q) == 1){ ...
block in the following way,
if (mysql_num_rows($login_q) == 1){
$row = mysql_fetch_array($login_q);
$_SESSION['username'] = $row['username'];
$_SESSION['user_id'] = $row['user_id'];
header('Location: http://ct6014-williams.studentsites.glos.ac.uk/pages-multi-page/home.php');
exit();
} else {
echo "<div id='loginmsg'>Wrong Password </div>";
}
Sidenote: Don't use mysql_*
functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli
or pdo
instead. And this is why you shouldn't use mysql_*
functions.
Upvotes: 2