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";
Related
I need to check which plant are online so I'm thinking to compare last date time update to the current time if difference is less than 15 min the plant is online otherwise is offline
I have write this in php to make a query but all row change to online or offline what I'm doing wrong?
it seams that the update is done on all row of the database not only in the selected by the first query
$sql = "select * from PlantData where lastUpdate > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
$resultt = mysqli_query($connection, $sql);
//echo($resultt);
while ($roww = $resultt->fetch_array()) {
$rowws[] = $roww;
}
foreach($rowws as &$roww) {
$sqlupdate = "update PlantData set statusConnection = 'online'";
mysqli_query($connection, $sqlupdate);
}
$sql2 = "select * from PlantData where lastUpdate < DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
$resultt2 = mysqli_query($connection, $sql2);
//echo($resultt);
while ($roww2 = $resultt2->fetch_array()) {
$rowws2[] = $roww2;
}
foreach($rowws2 as &$roww2) {
$sqlupdate2 = "update PlantData set statusConnection = 'offline'";
mysqli_query($connection, $sqlupdate2);
}
thanks for support
Run the query in only once
UPDATE PlantData
SET
statusConnection = CASE
WHEN lastUpdate >= NOW() - INTERVAL 15 MINUTE THEN 'online'
WHEN lastUpdate < NOW() - INTERVAL 15 MINUTE THEN 'offline'
END;
I have table as seen below:
ID, Date, Type
1, 2015-1-1, 2
2, 2015-5-1, 5
3, 2015-8-10, 4
(before 2015-1-1 .... type = default
2015-1-1 <= Date < 2015-5-1 .... type = 2
2015-5-1 <= Date < 2015-8-10 .... type = 5
since 2015-8-10 .... type = 4)
I would like simply check which type is for any $date.
I tryed:
$sql = "SELECT * FROM smlouvy
WHERE Date < '".$date."'
ORDER BY Date LIMIT 1";
$result = MySQL_Query($sql);
if ( mysql_num_rows($result) == 0 ) {
$type = 'default';
}
else {
$row = mysql_fetch_array($result);
$type = $row["Type"];
}
You can try something like:
select ID,date,
case `date`
when `date`<='2015-11-01' then 4
when `date`>='2015-11-01' then 5
else 1 end as `type`
from tbl;
Note: This is just an example,you may need to modify the conditions as per your requirement.
Here is solution (if Date column matches within a certain range):
$dateFrom = '2015-5-1';
$dateTo = '2015-8-10';
// exemplary query
$query = "SELECT type FROM table_name
WHERE $dateFrom <= Date < $dateTo
ORDER BY Date ASC LIMIT 1 ";
// it will return the type of lower date column from range (type = 5)
I am trying to get the records per current day, week and month in php mysql. The date column is of date type. The issue is here is that my week records and months records are getting same from below script. Here is my code, have a look.
public function getTodayComing(){
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date=DATE( NOW() ))
ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray ($sql );
}
public function getWeekComing() {
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date > DATE_SUB(NOW(), INTERVAL 1 WEEK)) ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray( $sql );
}
public function getMonthComing() {
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date > DATE_SUB(NOW(), INTERVAL 1 MONTH)) ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray( $sql );
}
Aah, I just saw it I think
date > DATE_SUB(...)
should be
date BETWEEN CUR_DATE() AND DATE_ADD(CUR_DATE(), INTERVAL 1 ...)
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);
}