I have a table in a database with the columns
d_monday, d_tuesday, d_wednesday, d_thursday, d_friday, d_saturday, d_sunday
The values for these are either 0 or Monday, Tuesday, Wednesday, Thursday etc depending on the day.
in my select statement I'm using
SELECT * from DEALS WHERE d_monday=DAYNAME(NOW()) OR d_tuesday=DAYNAME(NOW())
to find out whether the day name matches up with todays day, if it does then it returns results otherwise it doesn't display anything.
For some reason it's returning results when I haven't any value set for that specific day.
Any idea what could be the issue?
I would be tempted to pick the field using a PHP string
$day = "d_". date('l'); //lowercase L is full day name
$SQL = "SELECT $day FROM DEALS WHERE [...]";
I'm guessing a bit but would this not take you in the right direction?
Or something like this
$day = date('l'); //lowercase L is full day name
$SQL = "SELECT * from DEALS WHERE d_monday='$day' OR d_tuesday='$day' ";
It seems to me that you might want
$day = date('l'); //lowercase L is full day name
$SQL = "SELECT * from DEALS WHERE d_$day='$day'";
The format seems a bit messed up or maybe I just got the wrong end of the stick.
Hope that helps.
Consider removing your seven columns for the days of week and adding a separate table DealDays with a foreign key referencing Deals:
CREATE TABLE DealDays (
DealDayID int NOT NULL,
DealID int NOT NULL,
DayName varchar(10) NOT NULL, /* or, perhaps, enum ('Sunday', 'Monday', …) */
PRIMARY KEY (DealDayID),
FOREIGN KEY (DealID) REFERENCING Dels (DealID), /* or whatever is Deal PK's name */
UNIQUE (DealID, DayName) /* to make sure you can't add the same day twice per deal */
);
Then you would be able to find deals for the present day like this:
SELECT
d.DealID,
d.whatever,
…
FROM Deals d
INNER JOIN DealDays dd ON d.DealID = dd.DealID
WHERE dd.DayName = DAYNAME(NOW())
your query works fine. May be problem is in your data type of column(s) please check that.
My suggestion is that for that purpose you can use only one column so that your database is optimised.
Related
I am trying to update only the month and the day of a string. So example given: In my database i have a DATETIME column. Let's say that has the value 2018-01-08 00:00:00. The user gives in another date which he would like to update. E.g. 2017-11-07 00:00:00. I have a check on the code which descides if the date is different. So we'll skip that. I only want to update the month and the day of that string. So i don't want to update the time and year. The name of my DATETIME column is upDatum I've searched everywhere for this but there is no concrete answer. Here is what i have:
$query = "UPDATE twh_uren_prognose SET upUren =
".$key['inputupuren'].", MONTH(upDatum) = ".$month.", DAY(upDatum) =
".$day." WHERE upID = ".$key['inputupid'];
My question is: How can i only UPDATE the month and the day of a DATETIME MySQL column. I'm a little stuck. The Query which i'm talking about goes like this:
I hope this is kinda clear! Thanks!
You can try making a new date, using the day and month you entered in php and the year you allready had in mysql
$extraWhereTwee = ', MONTH(upDatum) = '.$month.', DAY(upDatum) =
'.$day.'';
$query = "UPDATE twh_uren_prognose SET upUren =
".$key['inputupuren'].", upDatum = STR_TO_DATE('".$day.",".$month.", YEAR(upDatum)','%d,%m,%Y') WHERE upID = ".$key['inputupid'];
Good afternoon lads, I am trying to make a page where I can check which bosses I did today. I have two tables (table with bosses and table with boss times). Now I need to show all bosses but for each of them I only want to show the closest time when the boss is going to spawn.
The select so far looks like that:
$timePlus = strtotime($currentTime) + 60*60*2.2;
$timePlusForm = date("H:i:s", $timePlus);
$userNametoLower = strtolower($userName);
$userTableName = "".$userNametoLower."_bosses";
$currentTime = date("H:i:s", time());
"SELECT `bossTime`.`ID`, `bossTime`.`bossID`, `bossTime`.`time`, `$userTableName`.`ID`, `$userTableName`.`name`,
`$userTableName`.`zone`, `$userTableName`.`map`, `$userTableName`.`waypointCode`, `$userTableName`.`bossDone`
FROM `bossTime` LEFT JOIN `$userTableName` ON `$userTableName`.`ID` = `bossTime`.`bossID`
WHERE `bossTime`.`time` BETWEEN '$currentTime' AND '$timePlusForm'
GROUP BY `bossTime`.`bossID`
ORDER BY `bossTime`.`time` ASC";
The problem is that this select does not pick the next closest value from time table. I also tried BETWEEN and it also didn't work (some bosses got correct closest time but other got the second closest). Any idea how to solve this is welcomed.
I removed GROUP BY and changed the condition to WHERE bossTime.time >= '$currentTime' AND bossTime.time <='$timePlusForm' and for some reason it works
I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?
Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();
You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)
It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.
let me explain my purpose first, i have an vehicle booking application where, visitor will add start date and end date of his journey, in the database there is list of drivers with there availability (available_from_date and available_to_date) which is kind of duration during which they are operating, there is an field for exclude_dates for some specific dates when they are not working.
the application needs to find a list of vehicles which are available during the journey dates entered by the user.
for example user enters he want to go from place A to B during 13th sept, 2014 to 17th sept, 2014
then database needs to return a list of taxi which are available during this period and must not have any exclude date within this period.
Now i have stored the exclude_dates in comma separated format in table (i could have created a separate table but then it would take much more time for a query to execute)
I was trying to create a mysql function which would be called within the actual search query and would return true if there is some there is some excluded date present within the duration and false if not.
these are the queries that i have written
SELECT id, exclude_dates
FROM `taxi_route`
WHERE status = 1
AND `to_city` = 'Surat'
AND `from_city` = 'Ahmedabad'
AND `trip_type` = 2
AND `available_from_date` <= '2014-09-13'
AND available_to_date >= '2014-09-17'
AND STR_TO_DATE((SELECT `split`(exclude_dates, ',', 1)),'%d-%m-%Y')
NOT BETWEEN STR_TO_DATE('13-09-2014','%d-%m-%Y')
AND STR_TO_DATE('17-09-2014','%d-%m-%Y')
Split is a function i have created in mysql to separate the dates present in comma format
DELIMITER $$
CREATE FUNCTION split( str VARCHAR(500), delchar VARCHAR(2), x INT )
RETURNS VARCHAR(500)
BEGIN
RETURN SUBSTR(SUBSTRING_INDEX(str, delchar, x),
LENGTH(SUBSTRING_INDEX(str, delchar, x-1))+IF(x > 1, 2, 1));
END$$
DELIMITER ;
this works fine as far as i pass 1 in split(exclude_dates, ',', 1) , but if the exclude_dates have more then one date then this will not work
can someone please suggest or guide, how this can be accomplished.
snapshot of database is here http://i.imgur.com/JaI8MSx.png
Your query is most likely going to take more time to execute than defining a separate table for exclusion dates. It's not a good practice using comma separated list inside a column for searching purposes, this is against normalization rules.
You should define your tables separately, (e.g. taxi, taxi_route, taxi_route_exclusion, route_exclusion) and later add necessary indexes to make your searches more efficient.
Example:
taxi
---------
id
country
***
***
***
taxi_route
-------------------
id
taxi_id
available_from_date
available_to_date
from_city
to_city
route_exclusion
---------------
id
taxi_id
exclusion_date
And also add a relation table between taxi_route and route_exclusion tables to represent many-to-many relationship. Later define foreign keys on taxi_route_route_exclusion table to point taxi_route and route_exclusion tables.
taxi_route_route_exclusion
--------------------------
taxi_route_id
route_eclusion_id
Define foreign keys like:
taxi_route.taxi_id -> taxi.id
taxi_route_route_exclusion.taxi_route_id -> taxi_route.id
taxi_route_route_exclusion.route_exclusion_id -> route_exclusion.id
Define indexes like:
taxi: IX1 (status, trip_type)
taxi_route: IX1(to_city, from_city, available_from_date, available_to_date)
Your final query should look like this:
SELECT tr.id, re.exclusion_date
FROM `taxi_route` tr JOIN `taxi_route_route_exclusion` trre
ON tr.id = trre.taxi_route_id
JOIN `route_exclusion` re
ON re.id = trre.route_exclusion_id
JOIN `taxi` t
ON t.id = tr.id
WHERE
t.status = 1
AND t.trip_type = 2
AND tr.to_city = 'Surat'
AND tr.from_city = 'Ahmedabad'
AND tr.available_from_date <= '2014-09-13'
AND tr.available_to_date >= '2014-09-17'
I have a list of business stored in a locations table, and stored in that table are hours the business opens and closes:
location
`mon_1_open`
`mon_1_closed`
`tue_1_open`
`tue_1_closed`
`wed_1_open`
`wed_1_closed`
ect...
I store the times in full hours and minutes, so say a business is open from 9:00AM to 5:30PM on monday.. mon_1_open = '900' AND mon_1_closed = '1730'.
I can't seem to figure out a way to find the day of week and output if the business is else open or closed based on the time of day.
Any suggestions?
This does not necessarily answer your question, but it may in the long run.
Your database scheme seems flawed. It definitely is not normalized. I would address that before it becomes a big issue, as you have noticed that it makes it hard to locate certain businesses hours. Here is a draft scheme that might be better suiting.
TABLE: locations
id INT AUTO_INCREMENT PRIMARY KEY
name VARCHAR(50)
TABLE: location_hours
id INT AUTO_INCREMENT PRIMARY KEY
location_id INT - Foreign Key references locations table
day CHAR(3) - (examples: mon, tue, wed, thu, fri, sat, sun)
hours VARCHAR(4) - (could also be int)
Then to get todays date, this can be done in MySQL with DATE_FORMAT %a, an example query:
SELECT locations.name, location_hours.hours
FROM locations
JOIN location_hours ON locations.id = location_hours.location_id
WHERE location_hours.day = DATE_FORMAT(NOW(), '%a')
AND location.name = 'Someway Business'
ORDER BY location_hours.hour
You should not need an open / close given that the the ORDER BY knows that 0900 < 1430 since it is a VARCHAR (although INT should know how to sort it as well), but your code when adding businesses will either need to update this record or you will need another field active to signify if that row should be used in the query. Just remember to use 24 hour time. Again this is a mock up, I just created it on the spot so it probably could use some improvements, but that would be better then doing a hack like you would have to with your current code.
UPDATE
Addressing the comment about finding if it is open or close:
Just use the PHP date function and call date('Hi') this will pull out the current time in 24-hour time, then you just do a simple if statement to see if it is between that, if it is, it is opened.
IE:
$sql = "SELECT locations.name, location_hours.hours
FROM locations
JOIN location_hours ON locations.id = location_hours.location_id
WHERE location_hours.day = DATE_FORMAT(NOW(), '%a')
AND location.name = 'Someway Business'
ORDER BY location_hours.hour";
$result = mysql_query($sql) or trigger_error("SQL Failed with Error: " . mysql_error());
$times = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($times['open'])) {
$times['open'] = $row['hours'];
}else {
$times['closed'] = $row['hours'];
}
}
$currentTime = date('Hi');
if ($times['open'] <= $currentTime
&& $times['closed'] > $currentTime) {
echo "Open";
}else {
echo "Closed";
}
Given that my logic is correct. Again, this is just pseudo code an example of usage. Given I just wrote it up on the spot. The above assumes you are only querying one business at a time.
$dayOfWeek = strtolower(date('D'));
$query = '
SELECT
location,
'.$dayOfWeek.'_1_open <= '.date('Gi').' AND
'.$dayOfWeek.'_1_closed >= '.date('Gi').' as is_open';
That should work.
However, you really should use a proper time datatype for the open/closed columns.