How can I change the grammar in mysql? - php

in my query
$stmt = $this->conn->prepare("SELECT p_index,m_id,DATE_FORMAT(trdDtTm, '%Y%m%d') as trdDtTm FROM ".$this->itemsTable." WHERE m_id = 2");$stmt->bind_param("i", $this->m_id);
result
{"items":[{"p_index":7,"m_id":"2","trdDtTm":"20220203"}}
However, if you search after changing the trdDtTm format, the results will not come out. How do I fix it?
$stmt = $this->conn->prepare("SELECT p_index,m_id,DATE_FORMAT(trdDtTm, '%Y%m%d') as trdDtTm FROM ".$this->itemsTable." WHERE m_id = 2 and trdDtTm = 20220203");
$stmt->bind_param("ii", $this->m_id, $this->trdDtTm);
no items.. how to fix it?

trdDtTm is a datetime column.
WHERE trdDtTm = 20220203
compares a datetime with a number hence. This makes hardly sense. Maybe you hope for the DBMS to magically match the two, but you shouldn't. Compare with a date literal instead:
WHERE trdDtTm = DATE '2022-02-03'
And if you want to find all rows on that date regardless of the time (the above only finds midnight, as DATE '2022-02-03' is considered equal to TIMESTAMP '2022-02-03 00:00:00'), do:
WHERE trdDtTm >= DATE '2022-02-03' AND trdDtTm < DATE '2022-02-04'

Related

Compare DATETIME MySQL with DateTime PHP

I have problems comparing dates between a date created with new dateTime () in php, and a date taken from a DATETIME field of a Mysql table.
With the following code, save a date in a DATETIME field of a MySQL table:
$now = new DateTime();
$update = $mysqli->query('INSERT INTO bonus (idplayer,lastlogin) VALUES ("'.$_GET["idplayer"].'","'.$now.'")');
Then I would like to retrieve the date from the tables and compare it with a date created using the php code:
$resetTime = new DateTime();
date_time_set($resetTime, 12, 00, 00);
$lastLogin = $mysqli->query('SELECT lastlogin FROM bonus WHERE idplayer = "'.$_GET["idgiocatore"].'"');
if ($resetTime < $lastLogin) {
echo "OK!<br>";
}
Using this code I can't comparate the dates because I get an error (I can't even do an echo of the date retrieved from the table).
Can anyone tell me where I'm wrong and how can I solve the problem?
Try this
$resetTime = (new DateTime)->format('Y-m-d 12:00:00'); //need it as a string
//$resetTime = date('Y-m-d 12:00:00'); //-- this is fine too
$stmt = $mysqli->parpare('SELECT lastlogin FROM bonus WHERE idplayer = ?');
$stmt->bind_param("s", .$_GET["idplayer"]);
$stmt->execute();
list($lastLogin) = $stmt->get_result()->fetch_array();
if ($resetTime < $lastLogin) {
echo "OK!<br>";
}
Basically your comparing the query result set, to your timestamp, instead of the value of the first column of the first row. Consider you code:
$lastLogin = $mysqli->query('SELECT lastlogin FROM bonus WHERE idplayer = "'.$_GET["idgiocatore"].'"');
if ($resetTime < $lastLogin) {
mysqli::query
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
https://www.php.net/manual/en/mysqli.query.php
Your also full of SQL Injection errors, an input such as this:
$_GET["idgiocatore"] = '" OR 1 ORDER BY lastlogin DESC LIMIT 1 --'
Will turn your query into this
'SELECT lastlogin FROM bonus WHERE idplayer = "" OR 1 ORDER BY lastlogin DESC LIMIT 1 -- "'
Everything after the -- is a comment so we can ignore that ending ". This avoids creating a syntax error, and is a very common tactic (nothing new).
This will select all records from the DB because Anything plus OR 1 is always true, then it will sort them by your lastlogin value DESC so the highest value is first and Limit to 1 return row, well just because I can. Basically this will satisfy your if condition if ($resetTime < $lastLogin) Which I guess is a "good thing" (well for me, the haxor).
Essentially this is because you are just pasting user input right into the SQL, so it becomes part of the command if formulated correctly (not a good thing for you).
Anyway Hope it helps you.
*PS it's been an age (like 6 years) sense I used MySqli (normally I use PDO) so forgive me any errors there, most of that came from a basic tutorial over at W3Schools
One last thing instead of setting the time, consider removing it altogether with the MySql DATE() function:
$resetTime = (new DateTime)->format('Y-m-d');
//...
$stmt = $mysqli->parpare('SELECT DATE(lastlogin) FROM bonus WHERE idplayer = ?');

Convert date in mysql

I have 'dob' field that is varchar type and the data is '12/07/1988' and '10/30/1988' inside my database.
I want to filter the record base on 'dob' date range.My input date range is '01/01/1988' and '31/12/1988' but all others record also come out.
This is my code,anyone can help?
SELECT
dob
FROM
`tblcustomers`
WHERE
DATE_FORMAT(STR_TO_DATE(dob, "%m/%d/%Y"), "%d/%m/%Y") >= '01/01/1988'
AND
DATE_FORMAT(STR_TO_DATE(dob, "%m/%d/%Y"), "%d/%m/%Y") <= '31/12/1988';
Thank you.
try it...
SELECT dob FROM tblcustomers where DATE_FORMAT(STR_TO_DATE(dob, '%m/%d/%Y'), '%Y-%m-%d') between '1988-01-01' and '1988-12-31'
It is better to use DATE/DATETIME than VARCHAR, otherwise it will waste time converting string to date all the time when you have queries.
You can simply change your dob field to DATE
and then filter the record like this
SELECT * FROM tblcustomers WHERE dob BETWEEN '1988-01-01' AND '1988-12-31'
Notice: When using BETWEEN...AND, '1988-01-01' & '1988-12-31' will not included
so you may decrease the start-day 1 day and increase the end-day 1 day
it may look like this
SELECT * FROM tblcustomers WHERE dob BETWEEN '1987-12-31' AND '1989-01-01'
or easier way similar to what you have done, this one is also possible
SELECT * FROM tblcustomers WHERE dob >= '1988-01-01' AND dob <= '1988-12-31'
Date range will work on sql date type not on varchar ,so first change it to date type and insert date in format yyyy-mm-dd then you can use range it will work
You can try this. I hope it will help you.
$from_date = date("Y-m-d",strtotime('01/01/1988'));
$to_date = date("Y-m-d",strtotime('31/12/1988'));
$query = "SELECT * FROM tblcustomers WHERE from_date >= '".$from_date."' AND to_date <= '".$to_date."'";

MySql Query for Current Date

I have s MySQL Query where I want to pull data from my database but base it on the current month information
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND DATE (lbs_date) = CURDATE()) ORDER BY lbs_date DESC LIMIT 0,50");
This string pulls out the information for the current day.
I have also tried the below string but get no results from it:
FROM lbs_trace_etrack WHERE (lbs_agent = '$slfirstname' AND MONTH(lbs_date) = (MONTH(NOW()) AND YEAR(lbs_date) = YEAR(NOW())
My table date format is as follow 2016-08-02
Or using PHP variables as so:
<?php
$start = date('Y-m-01'); // FIRST DAY OF CURRENT MONTH
$end = date("Y-m-t", strtotime(date("Y-m-d"))); // LAST DAY OF CURRENT MONTH
$sql = "SELECT * FROM lbs_trace_etrack WHERE lbs_agent = '".$slfirstname."' AND (lbs_date BETWEEN '".$start."' AND '".$end."')";
?>
I have done the following and it works
FROM lbs_trace_etrack WHERE lbs_agent = '$slfirstname' AND MONTH(lbs_date) = MONTH(CURDATE()) AND YEAR(lbs_date) = YEAR(CURDATE()) ORDER BY lbs_date ASC, lbs_time ASC
Thanks to all and Tijo for guidance
Assuming lbs_agent is a DATE field type as mentioned in comments, you could do this (note I am just showing the pertinent date part of your WHERE clause):
WHERE lbs_agent >= DATE_FORMAT(NOW() ,'%Y-%m-01')
It is important that you do not use a function call on the left (field definition) side of the WHERE comparison, as you will then not be able to leverage any index on that field. Doing this would require a full table scan with MySQL performing the function on this field for every row in the table such that the comparison can be made.
Feel free to use MySQL functions for the comparison value, as those would be calculated just once when the query is being planned. You would then be able to use an index on the field for quickly filtering the rows in the table that meet the criteria. From a query execution standpoint, this is basically that same as if your query has this WHERE clause:
WHERE lbs_agent >= '2016-08-01'
This is as compared to the examples in your question which would be executed as:
WHERE DATE(lbs_date) = '2016-08-03'
and
WHERE MONTH(lbs_date) = 8 AND YEAR(lbs_date) = 2016
Both of these would require full table scan since the values derived from the field are not able to be determined until the row is scanned.
You could try to extract the month, such as EXTRACT(MONTH from NOW())
you can use following code if it timestamp
MONTH(CURDATE())

Comparing date() in sql query

I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';

Using Date functions to pull records from database

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.

Categories