MYSQL Insert todays date to database - php

I' am running a query on table tblpages_copy to get the row datecreated and updating tblpages_copy2 in the same loop. For some reason in datecreated in the tblpages_copy2 it enters todays date.
I have checked the $date2 values and its prefectly fine its a correct value. The type of the datecreated in tblpages_copy is string
HERE IS THE QUERY
$i=0;
$q = mysql_query( "SELECT datecreated FROM tblpages_copy" );
while($row = mysql_fetch_array($q)){
$datecreated = $row["datecreated"];
$date = strtotime($datecreated);
$date2 = date('Y-m-d H:i:s', $date);
$q2 = mysql_query( 'UPDATE tblpages_copy2 SET datecreated = ' . $date2 . ' ');
if($q2){
echo $i++ .' '. $q2 . ' ' . $date2 . "<br/>";
} else {
echo mysql_error() . "<br/>";
}
}
MySQL error dump is
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 'xx' at line 1
What I suspect is that the Update query was wrong. I have tried few ways yet no luck
$q2 = mysql_query( "UPDATE tblpages_copy2 SET datecreated = '$date2'");
$q2 = mysql_query( "UPDATE tblpages_copy2 SET datecreated = ". $date2);

Try doing this, surrounding $date2 with ' and also using "'s for the query instead of ''s:
$q2 = mysql_query("UPDATE tblpages_copy2 SET datecreated = "' . $date2 . '" ");

Change
mysql_query( 'UPDATE tblpages_copy2 SET datecreated = ' . $date2 . ' ');
to
mysql_query( 'UPDATE tblpages_copy2 SET datecreated = "' . $date2 . '"');
and I bet it works. Dates are strings like anything else and must be quoted.

Try
'UPDATE tblpages_copy2 SET datecreated = "' . $date2 . '"'
Don`t use mysql_* functions. mysql_* functions are deprecated. You can use PDO and Mysqli

Related

php and mysql query to get date of the last 12 months

I have a php function to get dates for a morris pie chart and it was working fine.
But now that I have more data (date for the last year and the first 3 months of this year). It's now displaying duplicate months. In this case february of last year and this years data is now showing on the same pie chart.
I'd like to write a some mysql code in php that will only display the last 12 months. I have the following code:
function writesql($rec) {
$year = date('Y') -1;
$month = date('m');
$lastyear = $year - $month; // I know this is a problem.It's subtracting the two variables
$sql = "";
$sql = $sql . " SELECT";
$sql = $sql . " YEAR(`value`)as 'Year',";
$sql = $sql . " MONTH(`value`)as 'Month',";
$sql = $sql . " `value` , ";
$sql = $sql . " COUNT(`value`) as 'Calls' ,";
$sql = $sql . " ROUND(SUM( `value` ),2) as 'Value'";
$sql = $sql . " FROM `table`";
$sql = $sql . " GROUP BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)" ;
$sql = $sql . " ORDER BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)";
$sql = $sql." WHERE (`value`)='".$lastyear."'";// I also know this is wrong too but im lost as to how to fix it.
return $sql;
}
Then the rest follows, I only want to get the data for the last 12 months how should I be executing this.
You could do WHERE value >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR);
This would show 12 months up to the current date.
You are close. Make these changes
$year = date('Y') -1; // This will give last year
$sql." WHERE YEAR(`value`)='".$year."'"
Updated Query
$sql = "
SELECT YEAR(`value`) as 'Year', MONTH(`value`) as 'Month', `value`,
COUNT(`value`) as 'Calls', ROUND(SUM( `value` ),2) as 'Value'
FROM `table`
WHERE YEAR(`value`) = '$year'
GROUP BY YEAR(`value`), MONTH(`value`)
ORDER BY YEAR(`value`), MONTH(`value`)";
First off, I find this easier to read:
$sql = "
SELECT YEAR(value) Year
, MONTH(value) Month
, value
, COUNT(value) Calls
, ROUND(SUM(value),2) Value
FROM `table`
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value)
WHERE (value) = '".$lastyear."'
";
But this query is syntactically incorrect. So here's a syntactically correct version:
$sql = "
SELECT YEAR(`value`) Year
, MONTH(`value`) Month
, COUNT(value) Calls
, ROUND(SUM(value),2) Total_Value
FROM `table`
WHERE value = '".$lastyear."'
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value);
";
Now see about prepared and bound queries

Update SQL Datefield to add a week BUT keep same time

I have a countdown script that works 100% successfully. It's pulling the data down from the database but I'm having a few issues with a cronjob script. I want it to add a week to the community_night date.
When I try adding to this, it keeps resetting the date to 0000-00-00 however I can see that the query should be working correctly.
<?php
$con = mysqli_connect("localhost","","","") or die("Error in the consult.." . mysqli_error($connect));
$result = mysqli_query($con,"SELECT * FROM Community_Night");
while($row = mysqli_fetch_array($result))
$dbDate = $row['community_night'];
$date = strtotime($dbDate . ' + 1 week');
$setDate = date('d-m-Y',$date);
$sql = "UPDATE Community_Night SET community_night =" . $setDate;
if (mysqli_query($con, $sql)) {
echo "Record updated successfully: " . $sql;
} else {
echo "Error updating record: " . mysqli_error($con);
}
?>
the SQL column is set to DATE.
I haven't tested this, but it should work:
$sql = "UPDATE Community_Night SET community_night = community_night + INTERVAL 1 WEEK";
Bear in mind this will update all the rows in the table.

Display data according to dates in a table using PHP and Mysql

I am trying to display data in a table according to dates and currently am using the following code.
if($_GET){
$datefrom = $_GET['datefrom'];
$dateto = $_GET['dateto'];
$date0 = date('Y-m-d', strtotime($datefrom . " +0 days"));
$date1 = date('Y-m-d', strtotime($datefrom . " +1 days"));
$date2 = date('Y-m-d', strtotime($datefrom . " +2 days"));
$date3 = date('Y-m-d', strtotime($datefrom . " +3 days"));
$date4 = date('Y-m-d', strtotime($datefrom . " +4 days"));
}
Then I am querying my database repeatedly using the following statements
$stmtHR0 = $db->query("SELECT * FROM table WHERE Form_Date = '$date0' AND State = 'HR'");
$numHR0 = $stmtHR0->rowCount();
$stmtHR1 = $db->query("SELECT * FROM table WHERE Form_Date = '$date1' AND State = 'HR'");
$numHR1 = $stmtHR1->rowCount();
$stmtHR2 = $db->query("SELECT * FROM table WHERE Form_Date = '$date2' AND State = 'HR'");
$numHR2 = $stmtHR2->rowCount();
$stmtHR3 = $db->query("SELECT * FROM table WHERE Form_Date = '$date3' AND State = 'HR'");
$numHR3 = $stmtHR3->rowCount();
$stmtHR4 = $db->query("SELECT * FROM table WHERE Form_Date = '$date4' AND State = 'HR'");
$numHR4 = $stmtHR4->rowCount();
"HR" is just one of the states and I have 30 states to perform these queries on. The code works but I am wondering if there is a better way of doing this and I would be grateful if experts can help me on this. Please forgive me as I am still learning PHP.
This can be done with one query. Assuming From_Date field is DATE field type:
if ($_GET) {
$dateF = date('Y-m-d', strtotime($_GET['datefrom']));
$dateT = date('Y-m-d', strtotime($_GET['dateto']));
$sql = "
SELECT `From_Date`, COUNT(*) AS `count_num`
FROM `table`
WHERE `From_Date` BETWEEN '$dateF' AND '$dateT' AND `State` = 'HR'
GROUP BY `From_Date`
ORDER BY `From_Date` ASC
";
// db fetch all
}
try this code :
actually you can use array for date
$date = array();
$date[0] = date('Y-m-d', strtotime($datefrom . " +0 days"));
$date[1] = date('Y-m-d', strtotime($datefrom . " +1 days"));
$date[2] = date('Y-m-d', strtotime($datefrom . " +2 days"));
$date[3] = date('Y-m-d', strtotime($datefrom . " +3 days"));
$date[4] = date('Y-m-d', strtotime($datefrom . " +4 days"));
for($i = 0; $i<count($date); $i++{
$query_temp[] = "(
SELECT COUNT(*) FROM table WHERE Form_Date = '" . $date[$i]. "' AND State = 'HR'
) AS count" . $i;
}
$query = "SELECT " . implode(", ",$query_temp);
$stmtHR4 = $db->query($query);
hope this code can solve you problem

Count records from multiple tables in real-time

I want to count a record by current date from different tables and return as one row with different column in the new table. The code will update a record every three hours and insert new record if current date changes. I've current date and time data (2013-05-20 14:12:12) in "created_at" column. Here my current code:
require_once('./db_connect.php');
$dbcon = new db;
//test to see if a specific field value is already in the DB
public function in_table($table,$where) {
$query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
$result = mysqli_query($this->dbh,$query);
$this->error_test('in_table',$query);
return mysqli_num_rows($result) > 0;
}
//running in background
while (true) {
$select= "SELECT (SELECT CURDATE()) AS time," .
"(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
"(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
"(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";
$results = mysqli_query( $dbcon, $select );
while($row = mysqli_fetch_assoc($result)) {
$time = $row['time'];
$total = $row['total_count'];
$fcount = $row['f_count'];
$scount = $row['s_count'];
$field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;
if ($dbcon->in_table('count','time= "' . $time . '"')) {
$update = "UPDATE count SET $field_values WHEN time= '$time'";
mysqli_query( $dbcon, $update );
}
else {
$insert = "INSERT INTO count SET $field_values";
mysqli_query( $dbcon, $insert );
}
}
//update record every 3 hour
sleep(10800);
}
With this code I can't get a count record. The result return | 2013-05-18 | 0 | 0 | 0 |. How can I correct this?
I not familiar with PHP, but you can retrieve the count of all records dated any time today using:
SELECT COUNT(tweet_id)
FROM tweets
WHERE created_at >= curDate()
AND created_at < date_add(curDate(), interval 1 day)
It is equivalent to saying
..
WHERE created_at >= (today at midnight *incusive*)
AND created_at < (tomorrow at midnight *exclusive*)
Update:
The advantage of this method is it is index friendly. While using WHERE DATE(Column) = currDate() works, it can prevent the database from using indexes on that column, making the query slower.
Replace the parts where you have this:
WHERE created_at= 'CURDATE() %'
with this:
WHERE DATE(created_at) = CURDATE()
Your existing WHERE clause is comparing created_at to the string constant CURDATE() %, and they'll never match.
You are comparing against created_at= 'CURDATE() %', which is looking for that exact string, not for the result of a function. If the field created_at is a date, it will never match.
And, you are doing that for all counts.

while loop inside foreach loop problems

I'm trying to update a range of dates with a Shift_ID but the Shift_ID that is entered depends upon what day of the week it is. So, for example, if I have a range of dates $from = "2012-12-01" $to = "2012-12-28" I'm trying to make it so that I can select a check box (for example: value="Fri" name = "offdays[]") to indicate what day is an offdays. If an offdays is matched with a day in the set range, then the Shift_ID = "6" otherwise it is a work day and Shift_ID = "3"
Hopefully this will all make sense in a minute, I'm doing my best to explain it as well as give you some useful variables.
So here is my code:
if(isset($_POST['submit']))
{
if(isset($_POST['offdays']))
{
//$off is set through the config settings//
$shift = mysqli_real_escape_string($_POST['shift']);
$from = mysqli_real_escape_string($_POST['from']);
$to = mysqli_real_escape_string($_POST['to']);
$emp_id = mysqli_real_escape_string($_POST['emp_id']);
foreach($_POST['offdays'] as $checkbox)
{
echo "Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("SELECT Date FROM schedule WHERE (Date BETWEEN '$from' AND '$to') AND (Emp_ID = '$emp_id')");
if(!$result_date_query = $mysqli->query($sql))
{
echo "INSERT ERROR 1 HERE";
}
echo "SELECT SQL: " . $sql . "<br>";//error checking
while($row = $result_date_query->fetch_assoc())
{
echo "Date: " . $row['Date'] . "<br>";//error checking
$date = date('D',strtotime($row['Date']));
if($date == $checkbox)
{
echo "MATCHED! Date: " . $date . " Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("UPDATE schedule SET Shift_ID = '$off' WHERE Date = '" . $row['Date'] . "' AND Emp_ID = '$emp_id'");
if(!$result_update_offdays_query = $mysqli->query($sql))
{
echo "INSERT ERROR 2 HERE";
}
echo "UPDATE DAYS OFF SQL: " . $sql . "<br><br>";//error checking
}
else
{
echo "NOT MATCHED! Date: " . $date . " Checkbox: " . $checkbox . "<br>";//error checking
$sql = ("UPDATE schedule SET Shift_ID = '$shift' WHERE Date = '" . $row['Date'] . "' AND Emp_ID = '$emp_id'");
if(!$result_update_shift_query = $mysqli->query($sql))
{
echo "INSERT ERROR 3 HERE";
}
echo "UPDATE SHIFT SQL: " . $sql . "<br><br>";//error checking
}
}
}
}
}
When I look at my printed echo statements, everything is perfect! When a date lands on a Friday, it shows that it's entering Shift_ID = "6" and any other day shows Shift_ID = "3". The problem is the tables don't reflect what my statements are telling me, they all just get updated to Shift_ID = "3".
In the end I want to be able to select more than one offdays, but when I select more than one, it overwrites my previous day during the next loop, which makes sense.
I've got no idea what is going on, if anyone can give me a clue, I would really appreciate it.
UPDATE: When I add exit; after the days off update, like this:
echo "UPDATE DAYS OFF SQL: " . $sql . "<br><br>";//error
exit;
it does update the day off to Shift_ID = "6", so it must be something happening after that.
EDIT: It appears as though the problem was with user permissions. I can't explain why, but after deleting the user and creating a new one with full permissions, things started to work. I chose #andho's answer as he helped me get to the answer in the chat forum and also added a way to clean up my code.
This doesn't solve your issue, but simplifies the solution!
if your offdays variable is as follows: $offdays = array('Fri', 'Sun');
You can first set all dates in range to $shift in one query:
UPDATE Schedule SET Shift_ID = '$shift' WHERE Date BETWEEN '$from' AND '$to' AND Emp_ID = '$emp_id'
Then you can loop through the foreach ($offdays as $offday) { and update those offdays:
UPDATE Schedule SET Shift_ID = '$off' WHERE Date BETWEEN '$from' AND '$to' AND Emp_ID = '$emp_id' AND DATE_FORMAT(Date, '%a') = '$offday'
That should update all the $offday's in the range to $off.
This will reduce your loops and queries, which gives leaner code.
$sql = ("SELECT `Date` FROM schedule WHERE (`Date` BETWEEN '$from' AND '$to') AND (Emp_ID = '$emp_id')");
Use backtick(`) to all the fieldname date because it is reserved in mysql.

Categories