Calculate SUM in MySQL for todays date #Parse error - php

<?php
while($row=mysql_fetch_array($res))
{
//Result;
//select the sum in here;
$sumQry = "SELECT SUM(amount) FROM login WHERE tdate = '<?php echo date("F d, Y" ,time()); ?>" />' ";
}
?>
ERROR Parse error: syntax error, unexpected T_STRING in ... on line 4
i want to calculate the sum of numbers ( i mean like 10+50+85+90) for today date and diplsay the sum in fount end. so used the above code. but i think some thing wrong with <?php echo date("F d, Y" ,time()); ?>
UPDATE
Ok. Thanks guys! Leave about date. but i am not able to display the sum for total also.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ** on line 3
<?php
include "db.php";
while($row=mysql_fetch_array($res))
{
//Result;
//select the sum in here;
$sumQry = "SELECT SUM(amount) FROM login";
}
?>

I suggest you modify the MySQL table and use either DATE, DATETIME or TIMESTAMP.
They way you do it your field is CHAR or VARCHAR, that means indexing even if present will not work properly.
If you have the field as one of the above they can be indexed and performance of your query will be optimal even on a large number of records.
Thing is DATE, DATETIME and TIMESTAMP are stored numerically by MySQL. Also you will be able to sort by this field if you ever need to show more then a record and want to order by this field.
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". date("Y-m-d" ,time());
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". date("Y-m-d H:i:s" ,time());
$sumQry = "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = ". time();
I also added the MySQL fields quote because even if it's not necessarily most of the time, it is a good thing to use. If you have a large JOINed query it will perform up to 5% better with them. They are also good if you by any chance use reserved words as field names.
Your code should look like this:
include "db.php";
$res = mysqli_query($con, "SELECT SUM(`amount`) FROM `login` WHERE `tdate` = '". date("Y-m-d" ,time() . "' GROUP BY `ammount`;");
$row = mysqli_fetch_array($res);
echo $row[1];
In db.php you should have something like:
$con = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

If tdate is not an INT datatype in the db you need to encapsulate the value in quotes:
$sumQry = 'SELECT SUM(amount)
FROM login
WHERE tdate = "'.date("F d, Y" ,time()).'"';

Related

MySQL Query with UNIX_TIMESTAMP Not Working

I am trying to see if a field (end_date) in a MySQL database in the form of 2015-6-11 21:28:02 is greater than the current time. Essentially, is that field in the future or not.
Here is my PHP Code:
$current_time = time();
$sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < NOW()";
$result = mysql_query($sql, $db);
while ($row = mysql_fetch_assoc($result)) {
$echo $row['member_id'];
}
I keep getting an error:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /path/to/script.php on line 373.
Line 373 is the while ($row = mysql_fetch_assoc($result)) { part.
Any ideas of how this should be fixed?
Why not skip all that and just do this:
WHERE end_date < NOW()
Converting with UNIXTIME is extremely abusive on your database, it needs to evaluate that for every row in the table and cannot use indexes. The date field itself will evaluate very quickly if indexed.
You can also set your variable format to same format used in the database.
define('DATETIME_SQL', 'Y-m-d H:i:s');
$current_time = date(DATETIME_SQL);
$sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < $current_time";
FOUND IT!!!
In $sql = "SELECT member_id, course_id, FROM ".TABLE_PREFIX."vbc_status WHERE end_date < NOW()"; there is an unnecessary , after course_id.
Stupid syntax.... :)

Mysql Text to Date won't work

I got the following problem. I got a mysql field which is type "text" and there are many birthday dates in it.
I want to print the dates out and sort it in my way of date format. I can't change the type in the database because it's related to some user profile value fields.
The value's thats in the database are such this:
1978-12-31 23:59:59
This is my query:
$result = mysql_query("SELECT a.value, b.username from yrt6h_community_fields_values a join yrt6h_users b on a.user_id = b.id where a.field_id = 3 order by a.value;");
And this my example php file:
<table>
<tr>
<td>User:</td>
<td>Datum:</td>
</tr>
<?php
while($row = mysql_fetch_array($result)){
echo '<tr>';
echo '<td>';
echo $row['username'] . ' : ';
echo '</td>';
echo '<td>';
echo $row['value'];
echo '</td></tr>';
}
?>
</table>
I tried all of the date format functions of mysql, but then i got nothing.
For example I tried this:
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y'), ...
or
mysql_query("SELECT str_to_date(date_format(a.value, '%Y.%m.%d') %d.%m.%Y), ...
But I do that, the echo of the date is empty. Theres nothing to print out anymore. But why? Even if I put this query directly in the database I got NULL for the birthday value.
why dont you try to do it with php like -
echo date('d-m-Y', strtotime($yourDate));//the first paramete is the date format you want and the second is the value you are getting from database.
Reference for more understanding, example and formats.
Almost there!
I would suggest that you first get the data from the db with
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y')
Then
while($row = mysql_fetch_array($result))
{
$date = $row['date'];
$time = strtotime($date);
$formattedDate = date('Y-m-d', $time);
}
echo $formattedDate ;
Does that make senese?
Have you tried the PHP Date() function?
You could do something like so:
If you're looking for all records that match a specific date:
$timestamp = date('Y-m-d H:i:s'); //get current timestamp
mysql_query("SELECT * FROM `table` WHERE `timestamp` = '$timestamp'");
Or -- If you're trying to select/order by Timestamp:
mysql_query("SELECT * FROM `table` ORDER BY `timestamp`"); //select all order by timestamp
you can use mysql "cast" function.
rewrite the query in such a way:
"SELECT cast(a.value as DATETIME) new_dob,str_to_date(a.value, '%d.%m.%Y') dob from table_nm where cond"

Matching date and time from mysql - logic issue

I have uploaded a PHP script in the server. What it does is, that it keeps reading the DB (mySQL), and if the DATE_OF_MATCH and TIME_OF_MATCH (these are 2 fields in the mySQL db) is equal to the server time it will execute a message.
fields in the table: all are VARCHAR
ID, DATE_OF_MATCH, TIME_OF_MATCH, MATCH_NAME
One record from the MATCH table;
1 , 1/12/2012, 3:40, ManU vs Kaks
The problem is that, my select statement is wrong. My $theDateAndTime is returning 09:15:03PM and in the Database i am having 2 separate records for date and time. So how can i edit the select statement so could match the date and time against the $theDateAndTime (returned by the server)
The code:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
date_default_timezone_set('America/New_York');
$theDateAndTime = date("h:i:sA")."\n";
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$theDateAndTime." and TIME_OF_MATCH=".$theDateAndTime."");
while(true){
if(result!=null){
while($row = mysql_fetch_array($result))
{
echo $row['MATCH_NAME'] ;
echo "<br />";
}
}
}
mysql_close($con);
?>
I don't understand your question very well, but seems that you are trying to query for date and time in two different fields but you are only take the current time. I think you should try something like this:
<?php
$current_date = date('d/m/Y');
$current_time = date('h:i');
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$current_date." and TIME_OF_MATCH=".$current_time."");
Otherwise, you should not use mysql_* functions, use mysqli_* functions instead with prepared statements.
Create two separate variables for date and then time.
$the_date = date("n/j/Y");
$the_time = date("h:i:s");
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH={$the_date} and TIME_OF_MATCH={$the_time}");
http://us3.php.net/manual/en/function.date.php

Compare timestamp with date in php

i have this code which permits me to retrieve all the information in which the timestamp regarding that information is equal to another date.
Here is the code:
$information="SELECT * FROM scheda_anagrafica WHERE FROM_UNIXTIME('time_inserted','%d-%m-%Y') = '" . $giorno_selcted. "'
";
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
giorno_selected prints something like: 25-09-2012
What am i doing wrong here?
Thanks!
first of all, you should not use mysql functions on the left hand side of a operator in a where clause. this way mysql needs to read the complete table on disk to compute the value to compare with instead of optimizing the query for speed and resource usage (IO, cpu).
from your question and comments i understand, that you are querying the database for rows which have the same day as the string in your $giorno_selected represents. so you need to find all rows with timestamps between 0:00 and 23:59 on that specific day:
$giorno_timestamp_start = date_create_from_format('d-m-Y', $giorno_selected)->getTimestamp();
$giorno_timestamp_end = $giorno_timestamp_start + 86399; //add almost all seconds per day onto the start timestamp
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN " . $giorno_timestamp_start. " AND ". $giorno_timestamp_end;
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
this works if your time_inserted column is of type integer and holds unix_timestampds.
if it is of type datetime or timestamp you need to modify the query like this:
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN FROM_UNIXTIME(" . $giorno_timestamp_start. ") AND FROM_UNIXTIME(". $giorno_timestamp_end .")";

Comparing todays date to one listed in the database

I am using mysql and php to pull all the users out of the mysql database that are equal to todays date. The problem I am having is whenever I run the following code I get an error. By the look of the error is seems to be something to do with the year, or maybe it doesn't like the dots in it, but im not sure ?.
<?php
$today = date("d.m.y");
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date=$today")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['name'] . " " . $row['email']. " " . $row['date'];
echo "<br />";
}
?>
This is the error it is throwing :
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 '.12' at line 2
You have to add quotes around your date string:
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date='$today'")or die(mysql_error());
Need quotes around your $today variable. Also need to backtick the date column name since it's reserved.
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE `date`='$today'")or die(mysql_error());
First of all, $today should be added as a string into the SQL query:
mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = '$today'");
date is a SQL reserved word so it has to be escaped with backticks...
But I recomment using MySQL native functions and constants like NOW(), CURRENT_TIMESTAMP, SYSDATE etc...
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = NOW()
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` < NOW() - INTERVAL '2' DAYS
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` > NOW() + INTERVAL '5' HOURS
etc...
if you are using timestamp as datatype in mysql then you need to convert the date into unix timestamp first.
$today = strtotime("now");
or if you are using datetime or date data type then correct format is
YY-MM-DD, so you need to create the date accordingly.
$today = ('Y-m-d');
and also in your query you are missing single quote.
"SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = '$today'"
however you can compare the date without using PHP's date function, directly using MYSQL NOW().
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = NOW()
Try
$today = date("d-m-Y");
OR
$today = date("Y-m-d");
Also, check the format of date column is equal to the format of the return value of date().
If you have used DATETIME data type you may need to use matching format.
Also, wrap date value with single quotes...
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date = '" . $today . "'")

Categories