Matching date and time from mysql - logic issue - php

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

Related

How to get the sum in a column using MySQL and PHP

I've been searching for the better part of five days (no joke, don't want to bother you guys for nothing), but I can't seem to be getting this right. I want to display the total amount of a column (tech) on the screen using a function in PHP. Don't worry, the $day part works in other functions. I don't think it is part of the problem. Thank you in advance.
function calc_tech($day){
include("connect.php"); // include database connection
$res = $mysqli -> query(" SELECT * FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table
while($val = $res -> fetch_array()){
$tech_total = $val[tech] += $val[tech];
}
echo $tech_total; // Echo the result
//echo "42";
$res -> free(); // Free the query results
$mysqli -> close(); // Close mysqli object
}
My database table looks like this:
You need to make the SUM() the column in the query :
function calc_tech($day){
include("connect.php"); // include database connection
$res = $mysqli -> query(" SELECT SUM(tech) as sum FROM sales WHERE day = $day ") or die($mysqli->error); // Fetch data from the table
$val = $res -> fetch_array();
$tech_total = $val['sum'];
echo $tech_total; // Echo the result
}
1) '$day' should be enclosed by single quotes .
FOR SUM of column name query should be like this
"select sum(tech) as Toatal from sales where day='$day';"

Choose results by date filter PHP and MySQL

I have one page (members.php) that post date to another page (results.php). Using the below code, i can successfully get the "to" and "from" variables from the members page.
<?php echo $_POST["to"]; ?>
<?php echo $_POST["from"]; ?>
My problem now is, how can i create a query (in results.php) in order to show filter results only for the dates that are specified at the above variables? Do i need to create an sql connection and sql query too?
If dates are in YYYY-mm-dd format then you can use it as below otherwise you need to change the format.
You can do as below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//$from_date = $_POST['from_date'];
//$to_date = $_POST['to_date'];
$from_date = date("Y-m-d",strtotime('06/10/2015'));
$to_date = date("Y-m-d",strtotime('06/16/2015'));//$_POST['to_date'];
$query = "SELECT * FROM table WHERE from_date >= '".$from_date."' AND to_date <= '".$to_date."'";
// Perform Query
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
You should connect to database and compare this two dates:
$dateOne = $_POST["from"];
$dateTwo = $_POST["to"];
If bigger date is 0, then you should always make it the highest date possible to successfully query Data:
if(empty($dateTwo))
{
$dateTwo = date("31-12-Y");
//If $dateTwo is null, than it will be 31/12/2015 otherwise query will now work well
}
Then you should write sql query like this:
"SELECT * FROM `table` where `dateOne` > '$dateOne' and `dateTwo` < '$dateTwo'";
In this case if user wants all dates bigger than dateOne but doesn't check dateTwo, this query will return all data bigger than dateOne and lower than highest date available in current year (In our case it's 31/21/2015).
Its not necessarily creating a new sql connection but just a new query (proposed you have already connected to the database). In my opinion, if you want to display the results between the two dates.
I am not checking for existing or empty values since the dates have been already given.
So:
<?php $start_date = $_POST["from"];
$end_date = $_POST["to"];
//sql will be
$sql = "SELECT * FROM `your_table` WHERE `the_date_column` BETWEEN {$start_date} AND {$end_date}";
?>
Please but doing this use mysqli or PDO connection layer and also try to escape the variables to prevent sql injection or better off, use prepared statements.
SELECT * FROM sales WHERE build_date BETWEEN '$start_date' AND '$end_date';

Calculate SUM in MySQL for todays date #Parse error

<?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()).'"';

php mysql finding rows older than a day from date feald

Here is how it should be:
search the database for uploads older than a day.
output the id's for the uploads in a list.
here is what I have so far:
<?php
include 'config.php';
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$timestamp = strtotime("-1 days");
$efined = mysql_query("SELECT * FROM uploads WHERE timestamp < '$timestamp'");
$efound = mysql_query($efined);
$enum = mysql_numrows($efound);
$ecount = 0;
echo $enum.'records were found.';
while ($ecount < $enum) {
$euid = mysql_result($efound,$ecount,"uid");
echo $euid.'<br>';
$ecount++;
}
mysql_close($connect);
?>
currently, this outputs nothing, when there is a record 3 days old.
How would I spesify the date format? in my database, it looks like this: 2013-04-02.
thanks for any help,
josh.
this
$enum=mysql_numrows($efound);
should be
$enum=mysql_num_rows($efound);
EDIT.
try your sql like that
where timestamp < date('now', '-1 days')
edit:
you are defining two mysql_query
change this
$efined = mysql_query("SELECT * FROM uploads WHERE timestamp < '$timestamp'");
to
$efined = "SELECT * FROM uploads WHERE timestamp < '$timestamp'";
Your mistake...
$efined = mysql_query("SELECT * FROM uploads WHERE timestamp < '$timestamp'");
$efound=mysql_query($efined);
$enum=mysql_numrows($efound);
There must be only one query and wrong num_rows name...
$sql= "SELECT * FROM uploads WHERE timestamp < '$timestamp'";
$efound = mysql_query($sql);
$enum = mysql_num_rows($efound);
P.S. The old myslq functions support ends at PHP 5.4 . Its good for you to start using myslqi or PDO mysql !

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 .")";

Categories