So I am trying to compare today's date and the date of the last entry in the database. For some reason the code isn't working, and the comparison is always wrong.
$recentMood = mysqli_query($db_connection, "SELECT * FROM DemoUser ORDER BY date DESC LIMIT 1'");
$today = date('Y-m-d');
if($recentMood['date'] != $today){
mysqli_query($db_connection, "INSERT INTO DemoUser (Mood, date) VALUES('$mood' , NOW())");
echo "Mood recorded!";
}
else{
echo "Mood already recorded.";
}
P.S: When I try to echo either $today or $recentMood['date'], then I get an error. Any reason why that is?
You are comparing inside the if a resource to a date string.
if($recentMood['date'] != $today){
Fetch the results first:
$query = mysqli_query($db_connection, "SELECT * FROM DemoUser ORDER BY date DESC LIMIT 1");
if($query->num_rows > 0) {
$recentMood = $query->fetch_assoc(); // fetch it, you skipped this step
$today = date('Y-m-d');
$mood = $db_connection->real_escape_string($mood);
if($recentMood['date'] != $today){
mysqli_query($db_connection, "INSERT INTO DemoUser (Mood, date) VALUES('$mood' , NOW())");
echo "Mood recorded!";
} else {
echo "Mood already recorded.";
}
}
I believe that to make this work properly, you need to convert the date from the database into a usable timestamp.
if ($recentMood['date']) {
$past_mood = date('Y-m-d', strtotime($recentMood['date']));
}
$today = date('Y-m-d');
if($past_mood != $today){
mysqli_query($db_connection, "INSERT INTO DemoUser (Mood, date)
VALUES('$mood' , NOW())");
echo "Mood recorded!";
}
Related
I wanted to select a row in the database, but if row is not in the database, it should loop until it finds the
This line
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day')); transforms the currentdate to one down (lets say Jun 15, it will transform to Jun 14). And use that date to check if the date is in the database, it not, it will loop and go to Jun 13. Until it could find the date.
How do I do this? What loop should I use?
$query = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$macrodate'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 0) {
while(1) {
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day'));
$query2 = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$prev_date'";
$result2 = mysqli_query($con, $query2);
if (mysqli_num_rows($result2) != 0) {
$row2 = mysqli_fetch_assoc($result2);
$targetcarbs = $row2['carbs'];
$targetproteins = $row2['proteins'];
$targetfats = $row2['fats'];
$con->query("INSERT INTO users_macros VALUES('','$userid','$targetproteins','$targetfats','$targetcarbs','$macrodate')");
break;
}
}
}
Don't use a loop. Just use a query that returns the row with the highest date lower than $macrodate. And you can combine that with the INSERT query.
And add a NOT EXISTS criteria to make it select nothing if the given date is already in the table.
Also, use a prepared statement to prevent SQL injection.
$stmt = mysqli_prepare($con, "
INSERT INTO users_macros
SELECT '', userid, proteins, fats, carbs, ? FROM users_macros
FROM users_macros
WHERE userid = ? AND date < ?
AND NOT EXISTS (
SELECT 1 FROM users_macros
WHERE userid = ? AND date = ?
)
ORDER BY date DESC
LIMIT 1");
mysqli_stmt_bind_param($stmt, "sss", $macrodate, $userid, $macrodate, $userid, $macrodate);
mysqli_stmt_execute($stmt);
I am trying to find the particular date data from database,
my concept is if 2018-11-30 is given to find in database if the date is present in database it should display the date in output, if not present it should add +1 date to 2018-11-30 and try to find the next date 2018-12-01 like wise it goes on.
but i am facing the problem the date is not checked in the database.i am not sure weather my code is correct or wrong can any one give me solution for it.
this is my code
$Firstdate = '2018-11-29';
$Lastdate = '2018-12-03';
$Sql2 = "SELECT ScheduleDate FROM `empdet`";
$result2 = mysqli_query($con, $Sql2);
while($row = mysqli_fetch_array($result2))
{
if($row["ScheduleDate"]==$Firstdate)
{
$DBfirstdate==$Firstdate;
echo "$DBfirstdatebb",$DBfirstdate;
break;
}
else {
$checkFDBdate=date('Y-m-d', strtotime("+1 day", strtotime($Firstdate)));
if($row["ScheduleDate"]==$checkFDBdate)
{
$DBfirstdate=$checkFDBdate;
echo "$DBfirstdate",$DBfirstdate;
break;
}
}
}
$Sql3 = "SELECT ScheduleDate FROM `empdet`";
$result3 = mysqli_query($con, $Sql3);
while($row = mysqli_fetch_array($result3))
{
if($row["ScheduleDate"] == $Lastdate) {
$DBlastdate==$Lastdate;
echo "$DBlastdateBB",$DBlastdate;
break;
}
else {
$checkLDBdate=date('Y-m-d', strtotime("-1 day", strtotime($Lastdate)));
if($row["ScheduleDate"]==$checkLDBdate)
{
$DBlastdate=$checkLDBdate;
echo "$DBlastdate",$DBlastdate;
break;
}
}
}
$sql ="select * from empdet where ScheduleDate between '".$DBfirstdate."' and '".$DBlastdate."'";
$result = $con->query($sql);
SELECT ScheduleDate FROM `empdet` where ScheduleDate > '$Firstdate' and ScheduleDate < '$Lastdate' order by ScheduleDate limit 1
Try this way. You will get the first raw from the date range given.
Select stuff from somewhere where something > 'value' order by something limit 1
I have a PHP Script which is used to write data to a MYSQL Database.The Script retrieves the data from an Android app and write it to the database table.What I want is : the PHP script will calculate the count of data in the database table according to the date of entry and pass the count to the Android device according to which I need to do some validations in the Android App.Is it possible to do so in the same script? I mean is it possible to write data to a database table from an Android app on a button click and also read the data from the same script into the App.Can anyone please help me with this?
My PHP Script is:
<?php
require "conn.php";
require "SalesLogin.php";
$enquiry = $_POST["enquiry"];
$retail = $_POST["retail"];
$collection = $_POST["collection"];
$booking = $_POST["booking"];
$evaluation = $_POST["evaluation"];
$test_drive = $_POST["test_drive"];
$home_visit = $_POST["home_visit"];
$user_name = $_POST["user_name"];
$update_date = $_POST["date"];
$absent = $_POST["absent"];
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
$time = $date->format( 'H:i:s A' );
$sql = "UPDATE employee_details SET
enquiry_sum = (SELECT SUM(enquiry) +'$enquiry' FROM (SELECT * FROM employee_details WHERE date = CURDATE() AND name = '$user_name') AS x)
WHERE date = CURDATE() AND name = '$user_name'";
$res = $conn->query($sql);
$check = "UPDATE employee_details SET enquiry_target_status = ( SELECT IF (MAX(enquiry_sum) = 52, 'ACHIEVED', 'NOT ACHIEVED') FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Y ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($check);
$miss_count = "UPDATE employee_details SET enquiry_target_missed_by = (SELECT (50 - MAX(enquiry_sum)) FROM (SELECT * from employee_details WHERE date = CURDATE() AND name = '$user_name') AS Z ) WHERE date = CURDATE() AND name = '$user_name'";
$insert_status = $conn->query($miss_count);
$mysql_qry1 = "INSERT INTO employee_details(enquiry,retail,
collection,booking, evaluation, test_drive, home_visit, name, date,time,absent) values ('$enquiry','$retail','$collection','$booking','$evaluation','$test_drive',
'$home_visit','$user_name','$update_date','$time','$absent');";
if($conn->query($mysql_qry1) === TRUE)
echo "Your details has been successfully inserted.";
else
echo "Error: " .$mysql_qry1. "<br>" . $conn->error;
if($update_date != $date){
$mysql_qry2 = "UPDATE employee_data SET last_updated_date = (DATE_ADD('$update_date', INTERVAL 1 DAY)) WHERE name = '$user_name';";
$conn->query($mysql_qry2);
echo "Date changed," .$mysql_qry2;
}
$mysql_qry3 = "SELECT COUNT(*) from employee_details WHERE date = '$update_date' and name LIKE '$user_name';";
$conn->query($mysql_qry3);
if($mysl_qry3 <= 2)
{
echo "You can login.";
}
else
{
echo "You cannot login anymore for today.";
}
$conn->close();
?>
I want to check the condition and pass the result for the below part and make validations in Android App:
$mysql_qry3 = "SELECT COUNT(*) from employee_details WHERE date = '$update_date' and name LIKE '$user_name';";
$conn->query($mysql_qry3);
if($mysl_qry3 <= 2)
{
echo "You can login.";
}
else
{
echo "You cannot login anymore for today.";
}
The problem I was making is : I did not use "AS" keyword in the PHP Script.
The updated PHP Script is:
$mysql_qry3 = "SELECT COUNT(*) AS count from employee_details WHERE date = '$update_date' and name LIKE '$user_name';";
$result1 = mysqli_query($conn,$mysql_qry3);
$row = mysqli_fetch_assoc($result1);
$count = $row['count'];
echo "Count: " .$count;
if($count <= 2)
{
echo "You can login.";
}
else
{
echo "You cannot login anymore for today.";
}
This gives the desired result.
I have a function which fetches data from my database, it counts a number of instances existing for the same user and gives me a total figure. But I want to store this value in another table, which it does just fine the problem is that every time a user refreshes a page the same data is inserted and I want it to be inserted only once.
my function:
public function getYesterday($user){
$user = "SELECT user_id FROM tbl_user WHERE ott_email='$user'";
$query = mysqli_query($this->con(), $user);
$count = mysqli_num_rows($query);
if($count == 1){
while($row = mysqli_fetch_assoc($query)){
$id = $row['user_id'];;
}
$yesterday = "SELECT COUNT(tbl_template_log.user_id) FROM tbl_template_log ";
$yesterday .= "WHERE tbl_template_log.user_id='$id'";
$yesterday .= " AND DATE(send_date) = DATE(NOW() - INTERVAL 1 DAY)";
$query_yesterday = mysqli_query($this->con(), $yesterday);
$result = mysqli_fetch_row($query_yesterday);
$insert = "INSERT INTO tbl_statistics (user_id, sta_count, sta_date)VALUES ('$id', '$result[0]', NOW())";
mysqli_query($this->con(), $insert);
echo $result[0];
}
}
Looking at my function logic and structure could someone suggest a correct solution to make sure the insert query is done only once per day.....?
I am using PHP, and MySQL
i have the following problem with a login script. at the moment i refresh my site and would like to change mysql into mysqli. i have a working code, that works with mysql like it should to. now i get in trouble with changing that into mysqli, which doesn't work.
here is the original mysql code:
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
mysql_query("UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='$id'");
mysql_query("DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='$id'");
$result = mysql_query("SELECT COUNT(*) AS val FROM tableB WHERE ID='$id'");
$count = mysql_fetch_assoc($result);
var_dump($count);
if ($count [val] <xy){
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
mysql_query("UPDATE tableA SET x7=x7 + 1 WHERE id='$id'");
and here is the mysqli version, that wont work and i dont know why:
$time = gmdate("M d Y H:i:s", time());
$id = '".$row["id"]."';
$get_id = "SELECT id FROM tableA WHERE x1='".$x1."' AND x2='".$x2."'";
$result = mysqli_query($db, $get_id);
if ($result === false) {
printf("Errormessage 1");
exit();
}
$row = $result->fetch_array(MYSQLI_ASSOC);
$update = "UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='".$row["id"]."'";
$result2 = mysqli_query($db, $update);
if ($result2 === false) {
printf("Errormessage 2");
exit();
}
$reset = "DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='".$row["id"]."'";
$result3 = mysqli_query($db, $reset);
if ($result3 === false) {
printf("Errormessage 4");
exit();
}
$count = "SELECT COUNT(*) AS val FROM tableB WHERE ID='".$row["id"]."'";
$result4 = mysqli_query($db, $count);
if ($result4 === false) {
printf("Errormessage 5");
exit();
}
$sum = $result4->fetch_assoc($count);
var_dump($sum);
if ($count [val] <xy){
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
$update_x = "UPDATE tableA SET x7=x7 + 1 WHERE id='".$row["id"]."'";
$result5 = mysqli_query($db, $update_x);
if ($result5 === false) {
printf("Errormessage 5");
exit();
You haven't mentioned the actual error but it seems that problem occurs from here:
$row = $result->fetch_array(MYSQLI_ASSOC);
you didnot use a loop here like your mysql version of code.
You are attempting to insert $time into what appears to be a DATETIME column, based on your old mysql version, but it is improperly formatted.
$time = gmdate("M d Y H:i:s", time());
Based on your use of NOW() in the old code, we assume TableB.Date to be a DATETIME type:
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
So in your new code, since you don't use NOW() for the TableB insert, you should be creating $time as YYYY-MM-DD:
// Should be YYYY-MM-DDD H:i:s for MySQL
$time = gmdate("Y-m-d H:i:s", time());
// It gets inserted into TableB here
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
Or, just use MySQL's NOW() in the new code unless you have a reason to specify the time in PHP code:
$insert = "INSERT INTO TableB (Date, ID) VALUES(NOW() ,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('s', $id);
$query->execute();