fetch timestamp mysql value in $_SESSION - php

$qry = "SELECT user, TIME_FORMAT(last_login_time, '%H:%i') FROM login_attempts WHERE user = '".$username."'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0){
mysql_query ("INSERT INTO login_attempts(userid, user, attempts, last_login_time) VALUES('', '$username', '{$_SESSION['count']}', '{$_SESSION['login_time']}')");
}
else{
$row = mysql_fetch_assoc($result);
$_SESSION['login_time'] = $row["last_login_time"];
mysql_query ("UPDATE login_attempts SET attempts = '" .$_SESSION['count']."' WHERE user = '".$username."'");
}
In the above code I'm storing my $_SESSION['login_time'] value in 'login_attempts' table where the column name is 'last_login_time'.
Now I need to fetch this value and store it back in $_SESSION['login_time'] array so that I get to know when the last time user tried to enter. How shall I fetch this value???
The datatype of 'last_login_time' column is 'timestamp'.

You need to alias your TIME_FORMAT column in order to reference it.
SELECT user, TIME_FORMAT(last_login_time, '%H:%i') AS last_login_time ...
Also, why not UPDATE the login attempts to SET attempts = attempts + 1 ?

Related

Allowing a user to insert/post in database just once per day everyday

enter image description here
i have a database that has a table name as post and inside it i have a column named as date its data type is current time stamp, so i want each of my user to login to their account and click on a task once a day, and if they have already clicked for that day the insert query will work on the database just like they have inserted a data for that day and i dont want any insert to work for that particular user again if they have already inserted/posted for that day
here are my codes av tried but not working, please help
$status = "";
$date = "";
// POST
if (isset($_POST['pst'])) {
// receive all input values from the form
$status= mysqli_real_escape_string($db, $_POST['status']);
$date = mysqli_real_escape_string($db, $_POST['date']);
//the date here is the old date ie the last post the user has posted maybe yesterday so am using it to check for todays date
//Fetch user ID
$xyttq = $_SESSION['email'];
$sql = "SELECT id FROM users where email = '$xyttq'";
$result = mysqli_query($db, $sql);
// fetch the resulting rows as an array
$pizaq = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($pizaq as $pizq){
// echo ($pizq['id']);
$uidbq = ($pizq['id']);
}
// free the $result from memory
mysqli_free_result($result);
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM posts WHERE date ='$date' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
// if user exists am checking the database if the user has posted for that day
if ($user['date'] === $date) {
array_push($errors, "Already exists");
}
// Finally INSERT user if there are no errors in the form
else{
$query = "INSERT INTO posts (userid, status)
VALUES('$uidbq', '$status')";
$results = mysqli_query($db, $query);
}
}
It depends on what you store in your date column. If you store the time of post, then the time can vary and you need to check for the date range. You can check whether there are user's posts between today and tomorrow.
$today = strtotime('today');
$tomorrow = strtotime('tomorrow');
$sql = "SELECT count(*) AS no
FROM posts
WHERE userid = $uidbq
AND date > $today
AND date < $tomorrow";
Then you retrieve no from the query and check whether no is 0 or not.
This table prohibits the insertion of a user more than once per calendar day:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,user_id INT NOT NULL
,datetime_created TIMESTAMP NOT NULL
,date_created DATE NOT NULL
,UNIQUE(user_id,date_created)
);

How to record one vote per user php

So I am trying to write a php script that records one vote increment per user. Voters a are presented with a list of prospective candidates then clicks once on their name.
Now on attempt of a second time i hope to get a notification allowing this action. Please help.
<?php
if(isset($_POST['vote']))
{
$sql3='INSERT INTO sessions (memberID, postid, email, voted) VALUES ("","", "", 1;)';
$result3 = mysqli_query($con, $sql3);
}
// $count = mysqli_num_rows($result2);
$candidate_name = null;
$vote = $_POST['vote'];
mysqli_query($con, "UPDATE tbCandidates SET candidate_votes=candidate_votes+1 WHERE position_id='$vote'");
// $count = mysqli_num_rows($result2);
if ( $count<1) {
//$sql3='INSERT INTO sessions (memberID, postid, voted) VALUES ("", memberbers.memberID,"1")';
//$result = mysqlI_query("select id from Users where username ='".$_SESSION['email']."'");
//$result = mysqli_query($con, $sql3);
// $count = mysqli_num_rows($result2);
} else {
echo"You have voted already";
}
Put a "unique" flag on your memberID column in your SQL table. In that case when you try to insert a new row with the same memberID, it will not work.
Then catch the SQL write fail, and display a message if it gets to it.

Insert query not working with MySQL

I don't know if wrote something wrong in the query, or if it's a logic error. The problem is on the second to last line.
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
$num = mysql_num_rows($q1);
if($num==1){
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1)){
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(userId,visits,unique) VALUES('$userId','1','yes')");
?>
EDIT: userId and visits are both set to INT in the database.
i think first error in in variable name using in $ql and second is $num==1 if in visitors table multiple record of thats user then this condition will be wrong ($num==1) so i think replace it with this ($num>0)
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='$userId' ");
$num = mysql_num_rows($q1);
if($num>0)
{
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1))
{
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(`userId`,`visits`,`unique`) VALUES ('$userId','1','yes') ");
?>
You should add error handling to your sql queries, but the problem (after the correction indicated by #DanielLisik) is the use of a reserved word: unique.
Change your query to:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
You should also consider changing to PDO or mysqli as the mysql_* functions are deprecated.
1.
Change:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
to:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
2.
Delete the single quotes around $userId in your SQL queries (since it's an INT). It should be like this:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
and:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");

Updating a field after sending a mail

I have a reminder mail sent to those who do not log on to my site after 30 days. Earlier I got an answer on this forum to create a seperate field and then update it as mentioned here: Need help on unix time stamp.
I have created a new field lastprelogin, now how do I update the respective field when I send the mail for inactive users.
<?php
include("include/data.php");
$query = "SELECT * FROM myusers WHERE DATE_ADD(FROM_UNIXTIME(lastprelogin), INTERVAL 15 DAY) < CURDATE()";
$result = mysql_query($query);
$num = mysql_numrows($result);
$i = 0;
while ($i < $num)
{
//send mail code
$sendmail = mail($to,$subject,$msg,$headers);
$i++;
if($sendmail) {
$query1 = "UPDATE myusers SET lastprelogin='".time()."'";
$result2 = mysql_query($query1);
}
}
?>
How can I update the respective user's lastprelogin field after sending the mail?
I am lost here beccause am unable to understand the logic in this part.
You need to loop through your results by using mysql_fetch_assoc or similar function.
Your update query needs to include the ID of the record you wish to update.
You should not use the mysql_* functions anymore as they are becoming deprecated soon. Use mysqli instead
<?php
include("include/data.php");
$query = "SELECT * FROM myusers WHERE DATE_ADD(FROM_UNIXTIME(lastprelogin), INTERVAL 15 DAY) < CURDATE()";
$result = mysql_query($query);
while ($user = mysql_fetch_assoc($result))
{
//send mail code
$sendmail = mail($user['email_address'],$subject,$msg,$headers);
$i++;
if($sendmail){
$query1 = "update myusers set lastprelogin='".time()."' WHERE id = " . $user['id'];
$result2 = mysql_query($query1);
}
}
?>
The logic of Your script is simple:
retrieve all the users that didn't log in for last 15 days
send an email to each user
and if that succeeds also update the field lastprelogin for that user
You have some important errors within Your script and this should be like this:
include("include/data.php");
$query = "SELECT * FROM myusers WHERE DATE_ADD(FROM_UNIXTIME(lastprelogin), INTERVAL 15 DAY) < CURDATE()";
$result = mysql_query($query);
while($user = mysql_fetch_assoc($result)) {
// assuming that myusers table has these columns: user_id, user_name, user_email, lastprelogin
//send mail code
if(mail($user['user_email'],'Please log in','Please login to my site',$headers)) {
$query1 = "update myusers set lastprelogin='".time()."' where user_id = {$user['usri_id']}";
$result2 = mysql_query($query1);
}
}
// end.
As a $headers variable You can set a From header, etc. Look for PHP mail function here: http://php.net/mail
Also the right query for updating should be this one:
"update myusers set lastprelogin='".time()."' where user_id = {$user['user_id']}"
anyway You will update the lastprelogin of all users everytime...
You will need to get some id from your myuser table and run the update query with where id = $id.

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

Categories