Adding a timestamp into mySQL table - php

I am very new into LAMP environment and wanted to add the timestamp into the mysql table every-time any user logs into the system but I am having some typo issues. Part of my index.php file is below. Thanks!
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if($count > 0)
{
$_SESSION['uname'] = $uname;
**$timestamper = "UPDATE 'users' SET timestamp = CURRENT_TIMESTAMP() WHERE username='".$uname."'";
mysql_query($timestamper);
header('Location: home.php');**
}
else
{
echo "Invalid username and password";
}
}
My table looks like this: https://imgur.com/a/fblTkpY

Seems that you should have to alter your database schema also.
Let me explain you,
First add below columns to your db
is_login (datatype (enum) with values 0/1 )
last_login_datetime (datatype (timestamp), attibutes (on update current timestamp), default (current timestamp) )
Now when user logs in the system, set is_login flag to one and at the same time system will automatically update your last_login_datetime,
with the help of this, if future you can also use this is_login field in many terms and this will help you alot.

Related

Online Status for Multiple Users

I was able to do online status but works only for one user. When I login, it shows all users on users.php online even when they are offline.
Here is the Status Code:
session_start();
include_once 'db_connect.php' ;
if(isset($_SESSION['users'])) {
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = '$last' WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
}
$last = strtotime(date('Y-m-d H:s'));
$loggedtime = time() - 300; // 5 minutes
if($last > $loggedtime) {
echo '<font color="green" size="3px">online</font>';
} else {
echo '<font color="red" size="3px">offline</font>';
}
?>
I need help on how to make it work for multiple users.
Thanks. ;)
You have to use something like this:
$query=mysql_query("SELECT id FROM users WHERE last_login>NOW()-INTERVAL 30 MIN");
while($array=mysql_fetch_assoc($query)){
//Do something with the id's or the info you get for user who have there last login
//in the last 30mins
}
As #Crisp says in the comment above your query for last_login should be updated too, you can use mysql now() function like this:
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = NOW() WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
Note you have to stop using mysql_* as these functions are deprecated, start using PDO or mysqli

Is something wrong with my query?

I'm working on a database with 3 tables, some with overlapping information. A few columns from each table can be updated by the user via the web app that I am creating. But... There is an issue. Not sure what it is, but my updates aren't happening. I am wondering if something is wrong with my query. (Actually, after debugging, I am quite certain there is).
if (empty($errors)) {
$query1 = "UPDATE owner SET
name = '{$name}'
WHERE ownerId= '{$ownerId}'";
$query1_result = mysql_query($query1);
if (mysql_affected_rows()==1) {
$query2 = "UPDATE queue_acl SET
date_expires = '{$date_expires}'
WHERE user_id='{$ownerId}'";
$query2_result = mysql_query($query2);
if (mysql_affected_rows()==2) {
$query3 = "UPDATE ownerOrganization SET
orgId = {$orgId}
WHERE ownerId = '{$ownerId}'";
$query3_result = mysql_query($query3);
if (mysql_affected_rows()==3) {
$_SESSION['name'] = $name;
$_SESSION['updates_occurred'] = true;
}
}
}
Sorry if it is trivial; I have never worked with multiple tables before.
It's not a good habit to update tables the way you do it. If the updates are relating somehow you might want to think about creating a transaction. Transactions make sure that all updates are executed (and if not, a rollback is done (which means no update will be executed)):
// disable autocommit
mysqli_autocommit($dblink, FALSE);
// queries
$query1 = mysqli_query($dblink, "UPDATE owner SET name = '{$name}' WHERE ownerId= {$ownerId}'");
$query2 = mysqli_query($dblink, "UPDATE queue_acl SET date_expires = '{$date_expires}' WHERE user_id='{$ownerId}'");
$query3 = mysqli_query($dblink, "UPDATE ownerOrganization SET orgId = {$orgId} WHERE ownerId = '{$ownerId}'");
if($query1 && $query2 && $query3)
{
mysqli_commit($dblink);
$_SESSION['name'] = $name;
$_SESSION['updates_occurred'] = true;
}
else
mysqli_rollback($dblink);
I haven't tested it but it guess it should work. Also you should take a look at mysqli or prepared statements since mysql_ is deprecated.
The first issue might be scope related. Your if conditionals are wrong?
If (result ==1)
{
if(result == 2)
{
...
}
}
Thus if your first result is more than 1 then all the internal conditionals will be skipped.
If I understand it should be:
if(result ==1)
{
}
elseif(result ==2)
{
}
...(other conditions)...
else
{
}
I would recommend a base case to catch if you have more results than you expect.
The second issue might be that you quote around all data except orgId = {$orgId}. This should probably be orgId = '{$orgId}' if the id is some random string then not quoting will cause issues.
One last concern is to check ownerId. If that is blank for some reason then your query will fail because where id=0 (assuming you have auto increment on) will never be true. Put a if(!empty(ownerId) conditional.

PHP Login script problems with check if user banned

I'm getting errors with the PHP login script I am using on my site.
I wanted to add code which checks if the user is banned when he/she logs in.
But for some reason(s), it's not working properly; it always outputs "You are banned," even if the ban field/attribute contains on "n" for false in the MySQL "users" table.
I've tried fixing the code, but I still get errors. This is my code:
$bancheck = mysql_query("SELECT * FROM users WHERE ban = '".$_POST['username']."'" ) or die(mysql_error());
$ban = mysql_fetch_array($bancheck);
if ($ban = 'y') {
die('You are banned...');
}
The MySQL field which I've to check against is called "ban" and value is either "y" for "true," or "n" for "false."
1: Should be a comparison, not an assignment.
This line is incorrect:
if ($ban = 'y') {{
It should be:
if ($ban == 'y') {
I'm assuming there's an extra brace there by accident also.
2: SQL injection
You should not pass your string straight from $_POST into your MySql as you are vulnerable to SQL injection. You should escape it like so:
$bancheck = mysql_query("SELECT * FROM users WHERE ban = '".mysql_real_escape_string($_POST['username'])."'" )or die(mysql_error());
3: Ban != user
You should not compare ban to the username passed in via the form anyway, as ban will either hold the string 'y' or 'n'. You should compare the username (passed in) to the approriate username field in your database table. Like so:
$bancheck = mysql_query("SELECT * FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'" )or die(mysql_error());
4: Proper iteration & comparison
Instead of the mysql_fetch_array() function I'd use the mysql_fetch_assoc() function because it returns an associative array.
This will return an associative array for each row returned (contained in the MySql resource $bancheck) so you need to iterative through them (even though it should only return one array) like so:
while($ROW = mysql_fetch_assoc($bancheck))
{
if('y' == $ROW['ban']) {
die('You are banned...');
}
}
But I'd add in some more code just to help with any other problems:
$count = mysql_num_rows($bancheck);
if($count > 1)
{
die('More than one user with that username');
}
elseif($count > 0)
{
while($ROW = mysql_fetch_assoc($bancheck))
{
if('y' == $ROW['ban']) {
die('You are banned...');
}
}
}
else //i.e. $count<=0
{
die('No users with that username');
}
if ($ban = 'y') {{
should be
if ($ban == 'y') {
$bancheck = mysql_query("SELECT * FROM users WHERE ban = '".$_POST['username']."'" )or die(mysql_error());
this i think should be:
$bancheck = mysql_query("SELECT ban FROM users WHERE username = '".$_POST['username']."'" )or die(mysql_error());
if the column for username is called "username"
Learn about SQL injection hacker attacks. Go and do it now.
Are you checking the
right column in your inital statement? Should it not be "SELECT *
FROM users WHERE username =" or whatever? (as tveitan says)
$ban is an array. You need
$ban['ban'] instead to get the ban column. (as animuson says)
For comparison == not = (as adam says)
$bancheck = mysql_query("SELECT banned FROM users WHERE username = '". mysql_real_escape_string($_POST['username']) ."'") or die(mysql_error());
$ban = mysql_fetch_array($bancheck);
if($ban['banned'] == 'y') {
die('You are banned...');
}
Where banned ($ban['banned']) are your field with 'y' or 'n'.
But check the $_POST['username'] for mysql injection tries. See https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
To recap and expand, the assignment/comparison and the wrong column in the SQL WHERE clause are mistakes anyone will make from one time to another. The code snippet is still broken, though.
The PHP documentation for mysql_fetch_array states that the function returns an array containing the row where the databases internal pointer, not just a single value.
I'd do something like this
$username = do_some_injection_checking_or_escaping($_POST['username']);
$bancheck = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND ban='y';") or die(mysql_error());
if(mysql_num_rows($bancheck) == 1) {
die('You are banned...');
}
This is a good method if you just need to check something is there a certain number of times and you don't need the data.

Updating a table by using if condition - PHP - MySQL

Here am trying to update a field in a table with two values if the value which i got from other file using the GET function is Deactivate update the value of cnf_status as 1 and if it is Activate update the value of cnf_status as 0. But this bit of code is not working...can anyone help me how to solve this issue?
<?php
require_once '../config.php';
$id = $_GET['id'];
$status = $_GET['status'];
if($status == Deactivate)
{
mysql_query("update user_details set cnf_status='1' where user_id = '$id'");
}
else if($status == Activate)
{
mysql_query("update user_details set cnf_status='0' where user_id = '$id'");
}
?>
Forgot quotes maybe?
if($status == "Deactivate")
{
mysql_query("update user_details set cnf_status='1' where user_id = '$id'");
}
else if($status == "Activate")
{
mysql_query("update user_details set cnf_status='0' where user_id = '$id'");
}
You should also consider using mysql_real_escape_string() to avoid SQL Injections.
$id = mysql_real_escape_string($_GET['id']);
Usually you dont use Single quotes for Int fields... try removeing them.
You only need them when using with fields like: text, varchar, enum
Also you should quote the Deactivate & Activate otherwise they will be used as constants

mysql compare table values

I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query?
Try this:
$q = "SELECT id FROM table WHERE id = '".mysql_real_escape_string($_POST['user_id'])."'";
$r = mysql_query($q);
if(mysql_num_rows($r) > 0) {
echo "User ID was found in table";
} else {
echo "User ID was not found in table";
}
$qryResult = mysql_query("SELECT userid FROM idtable WHERE userid='$theIdOfUser'");
if (mysql_num_rows($qryResult) == 0)
{
// add a new vote
}
else
{
// notify the user that double voting is prohibited
}
Try not to use names like "id" to avoid conflicts with reserved words and related complications and need to use quotes

Categories