I've following query which updated the db table parkings to column name : latitude, longitude, parking_time and let_parked. So It's update all the column but it's not updating the parking_time column with NOW(). Do you know why ?
if(isset($_POST["update"]) && $_POST["update"]==true)
{
if($userid == "1")
{
$parking_time = "(NOW() - INTERVAL 122 MINUTE)";
$results = $mysqli->query("UPDATE parkings SET latitude = '$mLat', longitude = '$mLng', parking_time = '$parking_time', let_parked = '1' WHERE locId = '$mId' ");
}
elseif($userid == '0')
{
$parking_time = "NOW() - INTERVAL 220 MINUTE";
$results = $mysqli->query("UPDATE parkings SET latitude = '$mLat', longitude = '$mLng', parking_time = '$parking_time' WHERE locId = '$mId' ");
}
if (!$results) {
//header('HTTP/1.1 500 Error: Could not Update Markers! $mId');
echo "coudld not update marker." . mysql_error();
exit();
}
exit("Updated successfully Done! $userid, $mId");
}
Remove the () from around your date value, e.g.
$parking_time = "(NOW() - INTERVAL 122 MINUTE)";
should be
$parking_time = "NOW() - INTERVAL 122 MINUTE";
and then remove the ' from around where you use that datetime:
UPDATE [snip], parking_time = $parking_time,[snip]
^-- ^-- no quotes
This will eventually produce
UPDATE ... parking_time = NOW() - INTERVAL 122 MINUTE, ....
instead of
UPDATE ... parking_time = '(NOW() - INTERVAL 122 MINUTE)' ...
Your version was generating a string which contained some text. But since that text was treated as a string, MySQL would NOT execute the NOW() - ... date math, so you were trying to literally set your db field value to an invalid date.
Related
I'd like to only change the rows from the current hour on todays date.
// Have the current date
$date = "2019-03-21 17:14:03";
$rel = 8 // like an id.
$sql = "UPDATE graph SET code = '$code' WHERE myDate = '$date' AND rel = '$rel'";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
You can use the DATE_SUB function.
For example:
$sql = "UPDATE graph SET code = '$code' WHERE myDate >= DATE_SUB(NOW(), INTERVAL 1 HOUR)"
This will return all values where myDate is in the past hour.
Use DATE_FORMAT to compute the beginning of the current hour, and compare it against your datetime column. You don't need to pass the date as a parameter, you can get the current date/time with NOW():
UPDATE graph SET code = :code
WHERE myDate >= DATE_FORMAT(NOW(), '%Y-%m-%d %h:00:00') AND rel = :rel
You can do it in this way by ultilising HOUR() function in MYSQL:
$sql = "UPDATE graph SET CODE = '$code' WHERE DATE(myDate) = '$date' AND HOUR(NOW()) = HOUR ('$date') AND rel = '$rel'"
Im trying to do a mysql check if a record from $uid exist from today based on $timestamp and if it doesnt then do an INSERT.
//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
665414807 1369219044
tjt
//STEP 1 - do a look up on $uid and check with timestamp $today
$timestamp = $this->time;
$date = date('Y-m-d', $timestamp);
$today = date('Y-m-d');
$sql = "
SELECT * FROM vote WHERE
vote_fb_uid = '$this->fb_uid',
WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";
$res = mysql_query($sql) or die( mysql_error());
//STEP 2 - If no records are found for today - then we do an INSERT
if($no_record_for_today) {
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
}
Obviously im strugling with the SQL part for the look up - im wondering if there isnt some in-built SQL function to do this or similar?
to check if you had a vote in the last 24 hours :
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
if you want to limit to the same day (mean you are allowed to post at 2013.05.21 23:55 and 2013.05.22 00:05)
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Try this:
$today = date('Y-m-d'); //change it to timestamp if you want in timestamp
$sql = "
SELECT count(*) as total FROM vote WHERE
vote_fb_uid = '$this->fb_uid' and
vote_time = '$today'";
$res = mysql_query($sql) or die( mysql_error());
if($res[0]['total'] < 1){
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
} else{
//return error("custom","","Already Inserted.");
echo "already inserted";
}
Your $sql query have a syntax error, you have used two times clause WHERE the correct syntax to use two or more clauses in where is using AND to join them, to get only record wich don't have an entry for today you can use DATE_SUB with 1 day interval
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)
I have database "db2" with table "menjava"
In table menjava have "id", "author" and "date_submitted" field
id - auto_increment
author - int(11)
date_submitted - datetime
I want to count all the rows for todays date and all the rows for yesterdays date (so there will be two codes with conditions) based on a DATETIME field called 'date_submitted' that holds the date and time of each record's creation.
In the file result.php, there is this count displayed, but it does not work. In the same file (result.php) I have some other code to display data from different database, so I think that povezava.php is working ok.
My code:
<?
require "povezava.php";
$q=mysql_query(" SELECT COUNT(*) AS total_number FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)",$link2);
// now you can
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
$q=mysql_query($nt) or die(mysql_error());
}
?>
my file povezava.php looks like this:
<?
$servername='localhost';
$dbusername='user';
$dbpassword='pass';
$dbname1='db1';
$dbname2='db2';
$link1 = connecttodb($servername,$dbname1,$dbusername,$dbpassword);
$link2 = connecttodb($servername,$dbname2,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbusername,$dbpassword)
{
$link=mysql_connect ("$servername","$dbusername","$dbpassword",TRUE);
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
return $link;
}
?>
Error that I get:
A PHP Error was encountered
Severity: NoticeMessage: Array to string conversionFilename: templates/master.phpLine Number: 231 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
Fixed:
<?
require "povezava.php";
$q=mysql_query("SELECT COUNT(*) AS total_number FROM menjava WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY)",$link2);
// working
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
}
?>
Thank you!
Try :
$q = 'SELECT COUNT(*) FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)';
$result = mysql_query($q);
$total_rows = mysql_fetch_row($result);
print $total_rows[0] . ' authors have been submitted today and yesterday.';
Please try the following SQL commands:
$sqlToday = "Select COUNT(*) FROM menjava WHERE DATE(date_submitted) = CURRENT_DATE()";
$sqlYesterday = "Select COUNT(*) FROM menjava WHERE DATE(dc_created) = CURDATE() - INTERVAL 1 DAY";
I use this function it's very simple
function statsofdays($database,$tableName,$coloneDate,$past_days_to_count=0)
{
$datenow = date("Y-m-d H:i:s");
$stringDays = "(SELECT COUNT(Id) FROM `".$tableName."` WHERE DAY(".$coloneDate.") = '".add_date_to_date($datenow,'0 days','d')."') as day1,";
for ($i=2; $i <= $past_days_to_count; $i++)
$stringDays .= "(SELECT COUNT(Id) FROM `".$tableName."` WHERE DAY(".$coloneDate.") = '".add_date_to_date($datenow,'-'.$i.' days','d')."') as day".$i.",";
$row = $database->query("SELECT ".$stringDays." (SELECT COUNT(Id) FROM `".$tableName."`) as total");
$stringReturn[0] = $row['total'];
$stringReturn[1] = $row['day1'];
for ($c=2; $c <= $past_days_to_count; $c++)
$stringReturn[$c] = $row['day'.$c];
return $stringReturn;
}
Params :
$database :
You can modify the function has your database structure, for me i use
a class load to use ->query()
$tableName :
The name of the table you want to get data from
$coloneDate
Name of date format fields
$past_days_to_count
Number of days to go back to the past (if == 0 you get a count of total rows and today rows)
Example
$stats_of_year = statsofdays( $database , "table_name" , "creation_date" , 365 );
return
total rows for each day for 365 days like example (the values >= 0)
using
echo $stats_of_year['total'];
echo $stats_of_year['day1'];
...
echo $stats_of_year['day365'];
you need this also :
function add_date_to_date($stringDate, $days, $stringFormat)
{
$date = date_create($stringDate);
date_add($date,date_interval_create_from_date_string($days));
return date_format($date,$stringFormat);
}
in my code below i subtract the previous date of the user john in the field name date_time
from the current date CURRENT_TIMESTAMP the variable $newdate echo the answer in seconds only how can i make it to display from seconds to minutes from minutes to hours then hours to days
$query1 = "
SELECT (CURRENT_TIMESTAMP - date_time) AS dnew, date_time
FROM user
WHERE name = 'john'
";
$result1 = mysql_query ($query1) or die('query error2');
$line = mysql_fetch_assoc($result1);
$newdate = $line[dnew];
echo "$newdate";
$query1 = "
SELECT (CURRENT_TIMESTAMP - date_time) * 60 AS dnew, date_time
FROM user
WHERE name = 'john'
";
use math ( * 60)
I really need help on this one. I'm trying to do a mysql update based uisng case but i don't think i'm getting it right.
Here is what i'm trying to achieve.
I have a table with the following fields
user_id, rank, weekly, monthly, justwinners
1 9 0 0 0
2 29 0 0 0
3 8 0 0 0
4 10 0 0 0
5 12 0 0 0
What i want to achieve is to update the weekly, monthly and justwinners fields based on specific dates
Lets say i have a start date of 5/07/2011.
$startdate = 5-07-2011;
At the end of one week which is 12/07/2011 i want to update the weekly field of the user with highest rank to 1. Also at the same time update justwinners
field of the next 3 users with the highest rank to 1.
At the end of the second week which is now 19/07/2011, i want to update the weekly field of the user with highest rank whose value is still '0' to 2 and also update
the justwinners field whose value is still '0' to 2.
This will continue until i get to one months time when i will update the monthly field.
This is what i have been able to come up with so far which is not working.
//Initiate the database connection here
function get_db_conn() {
$conn = mysql_connect(HOST, DB_USER, DB_PASSWORD) or die('Could not Connect!');
mysql_select_db(DATABASE, $conn) or die ('could not connect to database');
return $conn;
}
function updateWinners( $limit, $field ) {
$conn = get_db_conn();
switch($field) {
case "weekly" :
$limit = 1;
case "monthly" :
$limit = 1 ;
case "giftpack" :
$limit = 10 ;
default:
$limit = 1 ;
}
$sqlquery = "SELECT * FROM application rank DESC " ;
$sqlquery .= " where $field < 1 ";
$sqlquery .= " LIMIT $limit ";
$result = mysql_query($sqlquery);
$user_data = mysql_fetch_row($result);
if(isset($user_data)) {
$user_data = 0 ;
while($user_data){
$uid = $user_data(user_id);
$rank = $user_data(rank);
$query = "INSERT INTO application_winners (user_id, rank, date) VALUES ('$uid', '$rank' 'now()')";
mysql_query($query) or die('Error, insert winners query failed');
switch ($action) {
case "weekly":
$startdate = "5-07-2011";
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN weekly = '1'
WHEN (CURDATE() = (startdate * 14))
THEN weekly = '2'
WHEN (CURDATE() = (startdate * 30))
THEN weekly = '3'
ELSE weekly
END";
}
$user_data = $user_data + 1;
} //endwhile
}
else {
echo "Error in updating the winners";
}
}
In case you know of any better way to implement this. kindly share.
Just as a remark - you have an insert followed by an update. You could do this in the insert part. Something like:
$query = "INSERT INTO application_winners (user_id, full_name, rank, date, $field) VALUES ('$uid', '$user_fullname', '$rank' 'now()', '$updatevalue')";
mysql_query($query) or die('Error, insert winners query failed');
i did not look at everything closely but you are using the variable "$action" for the second switch but it does not exist anywhere else in your code..
Try changing:
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN weekly = '1'
WHEN (CURDATE() = (startdate * 14))
THEN weekly = '2'
WHEN (CURDATE() = (startdate * 30))
THEN weekly = '3'
ELSE weekly
END";
to:
$sqlquery = "UPDATE application SET weekly = CASE
WHEN (CURDATE() = (startdate * 7))
THEN '1'
WHEN (CURDATE() = (startdate * 14))
THEN '2'
WHEN (CURDATE() = (startdate * 30))
THEN '3'
ELSE weekly
END";