MySQL Value as PHP Session - php

I have a registration script where the user id is saved as a session variable after registration and the user is redirected to their homepage. For some reason the user id is not being stored in the session variable. This exact same script worked on a different project, I simply took the project and changed the database connection settings and now it's not working.
Here is the registration script:
mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error());
// select the db
mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name));
// our sql query
$sql = "INSERT INTO seekers (first_name, last_name, username, email, password, salt) VALUES ('$firstName', '$lastName', '$username', '$email', '$hashedPW', '$salt');";
//save the updated information to the database
$result = mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));
if (!mysqli_error($link)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['user_id'] = mysqli_insert_id($link);
$_SESSION['loggedin'] = TRUE;
header("Location: ../index.php");
}
And here is the session checking and db query on the protected page:
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['user_id'] != 'user_id') {
include_once('includes/user.header.php');
//set user_id
$user_id = $_SESSION['user_id'];
//include the logged in user header
include_once('includes/user.header.php');
//select user information according to their logged in user_id
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
$row = mysqli_fetch_assoc($sql);
//create piece name together
$firstName = $link->real_escape_string($row['first_name']);
$lastName = $link->real_escape_string($row['last_name']);
$fullName = $firstName. " " .$lastName;
//get username
$username = $link->real_escape_string($row['username']);
When I am redirected to the index.php page, everything looks fine, except none of the user information is being queried from the DB.
Can anyone see what is wrong here? I know it's got to be something little and I'm just over looking it.
Please any help would be greatly appreciated.
EDIT: All information is being stored in the database successfully as well.

You are trying to use user_id without a select query ... indeed you must get the last insert id
changed line ;
$_SESSION["user_id"]=mysql_insert_id();
and
if (!mysqli_error($link))
should be
if (!mysqli_error($result))
and
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
to
$sql = $link->query('SELECT * FROM seekers WHERE user_id = "'.$user_id.'"');

Related

display database info on next page after loggin in using session

I'm new to PHP and I'm going to try to explain it the way I could :D. I'm trying to accomplish when the user logged in (using username and password), it opens a new page with the users name, address etc.
In my database table, I have a username, password, name and address.
I was able to accomplish the login page using session but would like to how to get/fetch those information like name and address to the new page it opens.
Thank you,
MD :)
correct me if i'm wrong.
Here is how u fetch the information from a certain table by using PHP and MySQL(PhpMyAdmin) database.
$conn = mysqli_connect("localhost", "root", "", "hotel"); //Connecting to the database
if($conn){
$sql = "SELECT USER_NAME, USER_PASS FROM USER"; //SELECT statement
$result = $conn->query($sql); //Executing the statement
if(mysqli_query($conn, $sql)){ //If query success
while($row = $result->fetch_assoc()){ //While loop to retrieve all data
$user = $row["USER_NAME"]; //Assign Column USER_NAME in database to $user
$pass = $row["USER_PASS"]; //Assign Column USER_PASS in database to $pass
echo $user."</br>".$pass."</br>"; //Displaying the content
}
}else{
echo "Query failed";
}
}else{
die("Fatal Error");
}
$conn->close(); //Close the database connection

I am trying to get the current session username to be inserted into a table PHP SESSIONS

Hi this has been frustrating me for a while and I can't seem to figure out what is wrong with my code
So I currently have a database called artworks and it has 2 tables within it a artwork table and a members table ( for login including username and password )
I already have login.php that stores username and password to the members table
Now I want to get that username from members table and store it within artworks table somehow. ( I do not know why my code is not storing my username into it)
<?php
session_start();
if(isset($_POST['title'])) $title = $_POST['title'];
if(isset($_POST['category'])) $category = $_POST['category'];
if(isset($_POST['description'])) $description = $_POST['description'];
if(isset($_POST['tags'])) $tags = $_POST['tags'];
$filename = $_FILES['image']['name'];
$location = $_FILES['image']['tmp_name'];
//move the file
move_uploaded_file($location, "uploads/$filename");
//put data into database
$db = mysqli_connect("localhost", "root","", "artworks") or die(mysqli_error($db));
$_SESSION['username'] = $username;
$q = "insert into artwork values(null, '$_SESSION[username]','$title', '$category', '$description', '$tags', '$filename')";
mysqli_query($db, $q) or die(mysqli_error($db));
//redirect
header("Location:gallery.php");
exit(0);
Ive also tried $_SESSION['username'] = $username; and $_SESSION['username'] = '$username'; and it still does not seem to work
I also want to display the current logged in user's name at the bottom of the page but echo $username also does not work ..
Many Thanks
should you do this, sign the $_SESSION['username'] at login section, i mean, after you success login, you create session with name => username and sign them from query's that refer to taking username and password from table member.
because session value still store although you change page, on the next page, refer to code above, you just include it to your query string.
for example
login.php
// u get data username and password from table member and asign it to $username
session_start();
$username = "foo";//you can sign this value from query tables
$_SESSION['username'] = $username;
remember, value on session still kept.
an in other side, on
store.php => it my assume ^_^
//after that $_SESSION[username] will be sign with name foo, for example
$q = "insert into artwork values(null, '$_SESSION[username]','$title', '$category', '$description', '$tags', '$filename')";
mysqli_query($db, $q) or die(mysqli_error($db));

how to get data(user details) from one table to another when the user is logged in

How do i get details from a table to another table when a user is logged in. The details include their names (first, last), email and uid. The table that I want to fetch data is from the data entered when the user was registering. So does my code make any sense or is there any other way to achieve what I'm asking for? I have also attached pictures.
My purpose for this is to know which user entered the amount (bidamount)
Data comes from:
Data goes to:
<?php
if (isset($_POST['button'])) {
$bidamount = $_POST['bidamount'];
$ratings = $_POST['ratings'];
//TO ALERT SUBMISSION OF BLANK FIELDS(IT DOESN'T PREVENT SUBMISSION OF BLANK FIELD THOUGH)
if (!$bidamount) {
echo "can't submit blank fields";
}
//TO CONFIRM YOU ARE CONNECTED TO YOUR DATABASE (OPTIONAL)
$connection = mysqli_connect('localhost', 'root', '', 'tickmill_auctions');
if ($connection) {
echo "we are connected";
} else {
die("connection failed");
}
// TO INSERT USER DETAILS IN THE TABLE
if (isset($_SESSION['u_uid'])) {
$uid = $_SESSION['u_uid'];
$query = "SELECT * FROM tickmill_auctions WHERE user = '$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$insert = mysql_query("INSERT INTO `son_of_man`
(`first`,
`last`,
`uid`,
`email`)
SELECT `first`,
`last`,
`uid`,
`email`
FROM `tickmill_auctions`
WHERE `user` = '$uid'");
}
}
//TO INSERT username and password from field to jossyusers database
$query = "INSERT INTO son_of_man(bidamount, ratings) VALUES('$bidamount','$ratings')";
$result = mysqli_query($connection, $query);
if (!$result) {
die("OOPPS! query failed" . mysqli_error($connection));
}
}
?>
You no need to add the full user detail in another table, read Normalization in SQL, just used the id of the user as foreign id to store the data in bid table. And then when you show the result on front view, you can use the JOINS to get the data from 2 tables.
And morevoer in query SELECT * FROM tickmill_auctions WHERE user = '$uid', there is no user field in any table.

MySql/PHP data not getting removed

<?php
session_start();
//get the location name/address.
$address = $_POST['table'];
$_SESSION['myaddress'] = $address;
$username = $_SESSION['username'];
//connection details.
$sev_host = "localhost";
$sev_username = "root";
$sev_password = "";
$sev_db = "mydata";
//Connecting server with db.
$conn = mysqli_connect($sev_host, $sev_username, $sev_password, $sev_db);
if (!$conn) {
die("Error : " . mysqli_connect_error());
}
//Check if the table exist, and if not then create the table
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);
$pre_insert = "update users set location='$address' where username='$username'";
mysqli_query($conn, $pre_insert);
$sql = "CREATE TABLE $address (id int(6) unsigned auto_increment primary key, username varchar(255) not null, src varchar(255) not null)";
$sql2 = "INSERT INTO $address (id, username, src) VALUES ('', '$username', '')";
mysqli_query($conn, $sql);
mysqli_query($conn, $sql2);
?>
This is my php code, and I seem to have a problem in it. This code is attached to a button and runs when it is clicked, but it's not giving me the required result. As you can see that I am deleting a row on $pre_remove statement, but when the code runs everything works except that the required row is not removed from the table.
The code works fine and it doesn't give out any debug errors. Any ideas?
The reason this doesn't work lies within your query on $pre_remove
A good way to debug your code, would be to use functions like var_dump, print_r etc. to see what your variables actually contains.
In this specific case, the problem lies within delete from $result_pre_check
$result_pre_check is not a variable. Again, you can do a var_dump($result_pre_check) to see what this variable is / contains.
Your query to delete a user based on username would however work if it was:
$pre_remove = "delete from users where username='$username'";
You can try something like this,
$pre_remove = "DELETE FROM users WHERE username IN (
SELECT location FROM users WHERE username='$username'
)";
mysqli_query($conn, $pre_remove);
instead of ,
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);

Unable to fetch and compare mysql data in php

I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>
Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.
I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.

Categories