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.
Related
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.
As the title says.
From the database, in the resultset, I want those rows where the date and time (schedule column) are already passed.
In the database I have
On the PHP page I have:
$now = time();
$result = $mysqli->query("SELECT * FROM schedules WHERE $now >= UNIX_TIMESTAMP(schedule)");
However, if I test this on 2015-09-19 at 18:50:00, I get no results at all, while instead I should only get the row with ID 39.
As much as I know I am comparing two valid timestamps - the one generated by time() and the one converted from the database with UNIX_TIMESTAMP() - so what isn't working?
EDIT: I already tried to do
$result = $mysqli->query("SELECT * FROM schedules WHERE NOW() >= schedule");
But with no luck. I am getting the results with
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
echo $id;
}
Use now() to select rows where schedule is in the past
SELECT * FROM schedules WHERE now() > schedule
They are different because,
php time is based on the php timezone setting (inside php.ini).
database time is based on your system time (unless you set it).
I am querying a database and displaying data. I have a timestamp and a Facebook ID that I use to display the user's profile picture (using the Facebook graph). This is more of a PHP/Loop question than a FB Graph question though. Here's my bit of code that I'm working on:
$sql = "SELECT * FROM fb_id ORDER BY timestamp DESC";
$result = $mysqli->query($sql);
echo "<h1>".$lastone_month." ".$year_lastone."</h1>";
while($row = mysqli_fetch_array($result)){
$fb_id = $row['fb_id'];
$timestamp = date_parse($row['timestamp']);
$month = $timestamp['month'];
$year = $timestamp['year'];
echo "<a href='http://www.facebook.com/".$fb_id."' target='_blank'><img src='http://graph.facebook.com/".$fb_id."/picture/' /></a>";
}
Eseentially what happens is I'm echoing the most recent month (this is in a bit of code before this). $lastone_month is a number (it's the number of the month of the most recent user that signed up). Let's say that it's January so the h1 would display 1/2013. I then have the while loop looping through the database and echoing out the user's profile picture in order of timestamp. What I would like it to do is to run the while loop until it reaches a row where $month is not equal to $lastone_month.
I can't use "&& $month==$lastone_month in the while loop because the $month value is not declared yet at that point. I tried an if statement around the echo line but that caused it to infinitely display one entry. I tried to declare row before the while loop and then declare $month and $year there too and then run the loop but that didn't work either. I'm thinking it's a really simple solution but I can't figure out what it is. Any help would be greatly appreciated. Thanks so much!
You can use break to quit from loop at any point:
while ($row = mysqli_fetch_array ($result))
{
...
$month = $timestamp ['month'];
if ($month != $lastone_month) break;
...
}
But more efficient is to use WHERE in your SQL query:
$sql = "SELECT * FROM fb_id WHERE MONTH(timestamp)='$lastone_month' ORDER BY timestamp DESC";
// build here timestamp which is your limit and name it $limit
$sql = 'SELECT * FROM fb_id WHERE timestamp < "$limit" ORDER BY timestamp DESC';
Something like that
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.
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().