Insert query inside if statement - php

I want to add the current date when a user is logged in on my system, however it doesn't seem to work!
if (password_verify($_POST['password'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
$query = " INSERT INTO accounts (last_login) VALUES (SYSDATE()
);WHERE `id`='".$id."'";
header('Location: home.php');
The field last_login field in MySQL is set to datetime. Now what happens is that it redirects the user to home.php, however nothing is written in the DB!

A few things to note:
I'd be surprised if you wanted to insert a record with only one value and no reference to the user account
INSERT doesn't use a WHERE clause
I'd expect you'd want to do an UPDATE
Perhaps something like this:
$query="UPDATE accounts SET last_login=NOW() WHERE id='".$id."'";

You may use NOW() Function in your query it will return the current date and time like
if (password_verify($_POST['password'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
$query = " INSERT INTO accounts (last_login) VALUES (NOW()) WHERE id='$id'";
header('Location: home.php');

Related

Correct way to update $_SESSION username in table

I've updated the post since I made a bit of change thanks to #user3282898! Though I still can't push the update to the DB.
The table column $id, $issue, $last_mod has already an existing content, I just need to update the content of issue andlast_modcolumn with respect to its$id`.
Here's what I have so far:
<?php
session_start();
session_regenerate_id();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
?>
<?php
$conn = mysqli_connect("localhost", "root", "", "order");
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
//id value
$id = $_GET['id'];
$last_mod = $_SESSION['username'];
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE id=".$_POST['id']) //update won't work
or die(mysqli_error());
header("Location: form.php");
}
else
{
header("Location: form.php");
}
?>
I've tried omitting the $last_mod to isolate the issue of updating and find that this statement works:
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved' WHERE id=$id")
However it won't work with $last_mod in it:
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE id=".$_POST['id'])
or
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE job_id=$job_id")
Your suggestion/opinion is always welcome, thanks in advance guys!
$_SESSION['username']='$last_mod'
You are updating the $_SESSION['username'] field in your table which does not exist!
The $_SESSION['username'] is the username and the column to be updated is the last_mod.
You should do this as i said in my comment:
UPDATE order.coupon SET last_mod='$last_mod' WHERE id='".$_POST['id']."'");
This should work for you.
$last_mod = $_SESSION['username'];
$query = "INSERT INTO coupon(last_mod)
VALUES ($last_mod)";
that query does not seem to make any sense; so how about ...
$sql = "UPDATE `coupon` SET `last_mod` = NOW() WHERE `coupon_id` = ?";
because it appears, as if you were trying to insert a username as the last_mod (last modification) timestamp of a coupon. just add a die($sql); whenever being uncertain why generated SQL won't work. besides, using the user_id (or the coupon_id) instead of the username would be suggested; because indexed INT fields are way quicker to query by.

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

update column in mysql database when user logs in

I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?
if (isset($_POST['login']))
{
$username = trim(mysqli_real_escape_string($con, $_POST['username']));
$password = trim(mysqli_real_escape_string($con, $_POST['password']));
$md5password = md5($password);
// check user and password match to the database
$query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
// check how much rows return
if (mysqli_num_rows($query) == 1)
{
// login the user
// get the id of the user
$fetch = mysqli_fetch_assoc($query);
// start the session and store user id in the session
session_start();
$_SESSION['id'] = $fetch['id'];
$_SESSION['username'] = $fetch['username'];
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
header("Location: message.php");
}
else
{
// show error message
echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
}
}
You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");
You need to change this:
UPDATE user SET loggedin = 'yes' WHERE userid = 1;
To this:
mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');
Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
You also use this:
if (mysqli_num_rows($query) == 1)
To check if the username exists, I suggest changing it to this:
if (mysqli_num_rows($query))
It does the same but you need less code to do it.
Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?

set session when user logs?

i am using a login script that is suppose to set a session when a user logs in. this session is called '$_SESSION['user']' and is a unique number stored in my table under 'session_number'.
$_SESSION['user'] = 'session_number'
Login Script (login.php):
<?php
include("config.php");
$tbl_name="supplier_pre_sign";
$myusername=$_POST['myusername'];
$myusername = stripslashes($myusername);
$myusername = mysql_real_escape_string($myusername);
$sql="SELECT * FROM $tbl_name WHERE code='$myusername' and status='active'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1){
session_start();
$_SESSION['user']=$myusername;
$_SESSION['username']=$row['firstname'];
if(isset($_SESSION['val']))
$_SESSION['val']=$_SESSION['val']+1;
else
$_SESSION['val']=1;
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$query = "SELECT * FROM supplier_session WHERE user_IP='$ip'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
}else{
$myusername = filter_input(INPUT_POST, 'myusername');
$ipaddress = $_SERVER["REMOTE_ADDR"];
$sql="INSERT INTO supplier_session (session_number, user_IP, date)
VALUES ('$myusername', '$ipaddress', NOW())";
$result = mysql_query($sql);
}
header("location:supplier_panel.php");
}else {
header('Location: index.php?msg=' . urlencode(base64_encode("Sorry That Code Wasn't Right!")));
}
ob_end_flush();
?>
Once the user logs in the session is suppose to be set. Now i am trying to use $_SESSION['user'] in my MYSQL Update where clause on a different page like so:
(register.php):
$sql="UPDATE supplier_session SET form1_completed = 'Yes' WHERE form1_completed = 'No' AND session_number = ".$_SESSION['user']."";
the problem i am getting is my mysql update script fails, with no error, but i am guessing $_SESSION['user'] is not defined and i somehow need to carry this session over to every page?
Can someone please show me where i am going wrong
One thing you might want to try is putting the session_start() call at the top of the script.
But why re-invent the wheel? This is especially true when it concerns security of your site. You're using database code that leaves you open to SQL injection attacks. I'm gonna guess you're storing user passwords in plain text too. You're just wide open for problems.
You really ought to go with something like http://www.php-login.net.

Changing boolean on login and logout

I posted a question today because i had problem with putting data in database on login, so that i can display the active users in my websites. So it happened to be one "," the problem. But it was suggested to me to use boolean in my database and if the user hasn't logged my bool called 'ifactive = 0'(deffault) , when user logs in 'ifactive=1'. So i made this transition from 0 to 1 on login and will show you part of the code:
if(isset($_POST['submit']))
{
$uname = mysql_escape_string($_POST['uname']);
$pass = mysql_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECT * FROM `userinfo` WHERE `uname` = '$uname' AND `pass` =
'$pass'");
if(mysql_num_rows($sql) > 0) {
mysql_query("UPDATE `userinfo` SET `ifactive` = 1 WHERE `uname` = '$uname'")
or die(mysql_error());
session_start();
$_SESSION['uname'] = $uname;
if (isset($_SESSION['uname'])) {
header('Location: main.php');
}
This part up of the code works correctly, sets the boolean "ifactive" to 1, (this code is in file named login.php, and after login it redirects me to my main page called "main.php". In "main.php" i have put a Logout button, which links to a "logout.php" file where i end the current user session and where i want exactly to reset my boolean "ifactive" to zero:
session_start();
mysql_query("UPDATE `userinfo` SET `ifactive` = 0 WHERE `uname` = '$uname'") or
die(mysql_error());
mysql_close();
session_destroy();
header("Location: index.php ");
But to make this mysql_query work i have to
include 'login.php';
So that i can use the variables. But here comes the main problem. When i include this login.php i suppose the two "Update" codes somehow fight and the second one doesnt work if you understand what i mean. And now i am reading about global variables but am for now confused about them. I mean to make my Update code in Logout.php work i suppose i do not have to include the whole login.php, i want to include only the variables:
$uname
so that it could be recognised
Store $uname in $_SESSION. Then you can just use $_SESSION['uname'] in your query:
session_start();
if(isset($_SESSION['uname'])) {
mysql_query("UPDATE `userinfo` SET `ifactive` = 0 WHERE `uname` = '$_SESSION['uname']'") or
die(mysql_error());
}
mysql_close();
session_destroy();
header("Location: index.php ");
Also, ifactive is an odd column name. I would go with active. Keep it simple. Then you your code looks like:
if($active) ...
instead of
if($ifactive) ...
Which seems like you have a stutter.

Categories