Conversion of dates in PHP and SQL - php

I am trying to get past fixtures for a football website. A user will add a fixture into the database and then I want the PHP script to return all fixtures that have a date older than or equal to today. This will then populate a drop-down to select the match and enter a score.
require 'connect-mysql.php';
$sql = $conn->query("SELECT
*
FROM
fixtures
WHERE
fixture_date <= " .date("Y-m-d"). "
ORDER BY
fixture_date DESC");
$rows = array();
while ($row = $sql->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows); // Parse to JSON and print.
The current output is nothing when I have database entries with a date of yesterday.
For example, I'd expect it to output a result if there was a fixture in there for today because I have put equal to also.

I want the PHP script to return all fixtures that have a date older than or equal to today.
Under most circumstances, you can probably trust that "today" for the user is the same as "today" on the database. There is no need to pass in the value. Just use curdate() or a similar built-in value:
SELECT f.*
FROM fixtures f
WHERE f.fixture_date <= curdate()
ORDER BY fixture_date DESC;

There's an error in your query, the quotes around the PHP date are missing. Try this:
$sql = $conn->query("SELECT
*
FROM
fixtures
WHERE
fixture_date <= '" .date("Y-m-d"). "'
ORDER BY
fixture_date DESC");
Better still: Check for MySQL errors.

Related

Check which table has the result in MySQL query, using PHP?

I am using the following MySQL query to check several tables for any results where the date is within 30 days.
What I want to do is be able to also check which table had the result, not just whether the MySQL query found a result in general.
One of my tables is supplier_bank_details, so if there is a record in this table with a date which is less than 30 days old then I am echoing out bank detail information, otherwise if it's my other table supplier_invoices then I want to echo out invoice information.
Here's what I have so far but I am really new to MySQL and struggling a bit. Please could someone show me what I would need to do to get this to work.
<?php require_once 'config.php'; ?>
<?php
$tbl_name = 'supplier_bank_details';
$tbl_name2 = 'supplier_invoices;
$query = "select * from $tbl_name, $tbl_name2 WHERE date > NOW() - INTERVAL 30 DAY ORDER BY date DESC";
$result = mysql_query($query) or die( mysql_error() );
$row = mysql_fetch_assoc($result);
if(mysql_num_rows($result) > 0) {
$datetime1 = new DateTime(); // Today's Date/Time
$datetime2 = new DateTime($row['date']);
$interval = $datetime1->diff($datetime2);
if(mysql_num_rows($tbl_name) > 0) {
$account_number = '****'.substr($row['account_number'], -4);
echo '<div class="contracts_area"><div class="table_header"></div>';
echo '<div class="request"><p>Bank Details Changed</p><p>'.$row['sort_code'].'</p><p>'.$account_number.'</p><p>about '.$interval->format('%d days ago').'</p></div>';
echo '</div>';
}else{
some invoice info here
}else{
echo '<div class="no_activity">No Recent Activity</div>';
}
}?>
Not too elegant, but you can add a constant field to your query, which refers to the table name:
select *,"tab1" as tablename from tab1
A column, called tablename will appear, wit with value of "tab1" in each row. It works only if there is least one record in the table.
Update: it's more useful, when you join different tables into a single result set.
Use separate queries if the data from both tables doesn't need to be merged together. Have one function to get supplier_bank_details over the last x days, another to get supplier_invoices over the last x days, and then you can handle any logic about what you want to show in PHP.

Querying Records in a Database with date parameters/variables

I'm making a website/database solution with database viewing/querying rights for the administrator.
I would like to give the user the option to insert two dates, with the page then producing all orders within the selected period.
I'm aware of how to retrieve variables from a form, it's the back end stuff I'm unsure about and applying the dates to the records.
An example to maybe get you going in the right direction:
$results = mysql_query(
sprintf("
SELECT [your fields]
FROM [your table]
WHERE [date field] > '%s'
AND [date field] < '%s'",
mysql_real_escape_string($enteredStartDate),
mysql_real_escape_string($enteredEndDate)
)
);
Edit:
Dates should be in the format "YYYY-MM-DD HH:MM:SS".
Example fetch / display:
while ($row = mysql_fetch_assoc($results)) {
echo $row['fieldName'];
}
You of course need to be connected to a DB for any of this to work, see PHP Manual mysql_connect
If you are still having problems I think you need to do some reading on using PHP / MySQL, a simple Google search gives a whole stack of possible reading material.
use sql between operator,
where table.date_column_name BETWEEN '$startDate' AND '$endDate'
This query will do -
$query = SELECT * FROM table_name WHERE create_time <= '" . $EndDate . "' and create_time >= '" . $StartDate . "';
where create_time is the the field in your table where you save date and time

A logical problem with two tables

Hey guys, I created a list for fixtures.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
$d = "Start";
while ($row = mysql_fetch_assoc($result))
{
$odate = $row['date'];
$date=date("F j Y", $row['date']);
echo "<p>Fixture $i - $d to $date</p>";
}
As you can see from the query, the date is displayed from the fixtures table.
The way my system works is that when a fixture is "played", it is removed from this table. Therefore when the entire round of fixtures are complete, there wont be any dates for that round in this table. They will be in another table.
Is there anyway I can run an other query for dates at the same time, and display only dates from the fixtures table if there isnt a date in the results table?
"SELECT * FROM ".TBL_CONF_RESULTS."
WHERE compid = '$_GET[id]' && type2 = '2' ORDER BY date"
That would be the second query!
EDIT FROM HERE ONWARDS...
Is there anyway I can select the date from two tables and then only use one if there are matches. Then use the rows of dates (GROUPED BY) to populate my query? Is that possible?
It sounds like you want to UNION the two result sets, akin to the following:
SELECT f.date FROM tbl_fixtures f
WHERE f.compname = '$comp_name'
UNION SELECT r.date FROM tbl_conf_results r
WHERE r.compid = '$_GET[id]' AND r.type2 = '2'
GROUP BY date
This should select f.date and add rows from r.date that aren't already in the result set (at least this is the behaviour with T-SQL). Apparently it may not scale well, but there are many blogs on that (search: UNION T-SQL).
From the notes on this page:
//performs the query
$result = mysql_query(...);
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise,
//returns an array containing the selected fields and their values
if($num_rows == NULL)
{
// Do the other query
}
else
{
// Do your stuff as now
}
WHERE compid = '$_GET[id]' presents an oportunity for SQL Injection.
Are TBL_FIXTURES and TBL_CONF_RESULTS supposed to read $TBL_FIXTURES and $TBL_CONF_RESULTS?
ChrisF has the solution!
One other thing you might think about is whether it is necessary to do a delete and move to another table. A common way to solve this type of challenge is to include a status field for each record, then rather than just querying for "all" you query for all where status = "x". For example, 1 might be "staging", 2 might be "in use", 3 might be "used" or "archived" In your example, rather than deleting the field and "moving" the record to another table (which would also have to happen in the foreach loop, one would assume) you could simply update the status field to the next status.
So, you'd eliminate the need for an additional table, remove one additional database hit per record, and theoretically improve the performance of your application.
Seems like what you want is a UNION query.
$q1 = "SELECT DISTINCT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name'";
$q2 = "SELECT DISTINCT date FROM ".TBL_CONF_RESULTS.
"WHERE compid = '$_GET[id]' && type2 = '2'";
$q = "($q1) UNION DISTINCT ($q2) ORDER BY date";

Looping out mysql data

I have a mysql database of entries with dates. So what I want is to show all the dates in my database and then under each date, I want to show all the entries in the database entered on the specefic date. I am thinking of two loops but I don't know how to write the condition to display all the dates in my database before I loop out the entries under that date.
Edit: i used NOW() to store the date. Using the loop by longneck, how can ignore the time when checking if date is sameas previous? Should I explode? What's the best way?
you should use one query, sort it by date, and detect the change in the date as a signal to display the next date:
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date'];
}
echo "<p>{$row['name']}</p>";
}
?>
I'm assuming that you want a list of the dates so that you can then do separate queries for each date's entries. Usually you would use a query like:
SELECT DISTINCT date_field FROM table_name ORDER BY date_field DESC
(this will do it newest-first, remove DESC to make it oldest-first)
Now, you probably don't want to do it this way, because it will require a lot of queries (one for each day's entries). It is more efficient to just order the entries by the date, and then use logic in your php to print out the headers. So you would use code like:
$result = $db->query("SELECT * FROM table_name ORDER BY date_field DESC");
$current_date = "";
while ($row = $result->fetch_array()) {
if ($current_date != $row["date_field"]) {
echo "<h3>{$row['date_field']}</h3>";
$current_date = $row["date_field"];
}
// Print your entry from $row here.
}
you would probably want to get that in your SQL statement: (assuming it is datetime type)
SELECT * FROM table
WHERE date BETWEEN '2009-9-8 00:00:00' AND '2008-9-8
23:59:59'
Then just do your normal loop through your results
Also have a look at the GROUP BY clause of the SELECT statement.

How can I ignore time for NOW()?

I have a mysql database of entries
with dates. So what I want is to show
all the dates in my database and then
under each date, I want to show all
the entries in the database entered on
the specefic date. I am thinking of
two loops but I don't know how to
write the condition to display all the
dates in my database before I loop out
the entries under that date.
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) { if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date']; }
echo "<p>{$row['name']}</p>"; }
?>
In a previous question (Looping out mysql data), I resulted in using this code. It pulls the date and time from MYSQL, and I used NOW() to store both date and time. How can I make it ignore the time so I can achieve what I want?
as David Andres mentions in the comment, DATE() extracts the date part of a date or datetime expression. so you can do the following:
<?php
$sql = 'SELECT DATE(start_date) AS start_date_date, name FROM events ORDER BY start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date_date'] != $prev_date) {
echo "<h1>$row[start_date_date]</h1>\n";
$prev_date = $row['start_date_date'];
}
echo "<p>$row[name]</p>";
}
Use CURDATE() instead of NOW().
Try it with a condition like this:
SELECT * FROM `events` WHERE DATE(`start_date`) = '2009-09-09';
This'll get you all events from the database for Sep 9th 2009. I think that's what you're asking for, is it?
Untested code that I will probably need someone to correct, but here goes:
SQL to retrieve all the dates that exist in the table:
$sql_get_dates = 'select start_date from events order by start_date distinct';
And, assuming start_date is a DATETIME type, the SQL to get all events on a given date:
$sql_get_events = 'select * from events where date(start_date) = "2009-08-09"';
Instead of just selecting the date, you could use some of the MySQL time functions to truncate the date.
$sql = "select date_format(start_date, '%Y-%m-%d') as fstart_date, name from events order by start_date";
Of course, you'll have to change start_date to fstart_date within the PHP code.
Check out the Mysql reference page for DATE_FORMAT().

Categories