Sql Query Not Working with php variables - php

My Sql Query Returning Empty results set. Is there any Mistake in format. I am Using some php variables inside the query..
public function getBlockDate($month,$year){
$connection = db::factory('mysql');
$time_from="00-00-00";
$time_to="23-59-59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
return $connection->getArray($sql);
}
*Here time_from and time_to table columns are of time type*

Change your SQL query
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
' single quotes are missing over $time_from and $time_to
EDITED QUERY
$time_from="00:00:00";
$time_to="23:59:59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" BETWEEN (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
also change the - with : in your $time_from and $time_to variables

This should work for you. You didn't put quotas right at the AND clause.
Also when using LIKE in your query be sure to place the wildcard correctly. In your case you are looking for records in date column whose start with year-month then there's your time.
$time_from="00-00-00";
$time_to="23-59-59";
$sql = "SELECT * FROM blocks WHERE date LIKE '".$year."-".$month."%' AND (time_From='".$time_from."' AND time_to='".$time_to."')";

Convert date and time to universal format and then query using it.

Related

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';

Select rows between two dates where dates are variables

I have an SELECT statement in php and I need to select all rows of the table where the "date" column is in between a start date and end date that will be defined by variables.
I have this working perfectly fine when I define the dates directly in the SELECT statement as shown below:
date BETWEEN "2015-02-03" AND "2015-02-05"
However, when I try to do the same thing but with variables, it doesn't seem to work:
date BETWEEN "$startdate" AND "$enddate"
Where
$startdate = "2015-02-03";
$enddate = "2015-02-05";
Hope all this makes sense, Cheers in advance.
Full code snippet is here as requested:
$startdate = "2015-02-03";
$enddate = "2015-02-05";
$sql = 'SELECT record_number, date, manmod, description, cal, serial, datein, dateout, retdate, refex, refexdate, sellersname, sellersaddress, buyersname, buyersaddress, rfddealer, del, warranty, months FROM record WHERE del="Live" AND date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
From the PHP website:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
In other words, since your query is in single quotes, the $startdate and $enddate variables are not interpreted as variables. The SQL query that is send to the database will literally contain $startdate and $enddate, and will therefore look something like this:
'SELECT column1, column2 FROM table WHERE date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
(I've simplified the query a bit for readability purposes)
Obviously, the database does not know how to interpret PHP variables, it will look for records with a date between those two strings, finds nothing and therefore returns 0 records.
In order to paste the contents of the variables in your SQL query, you will have to do one of two things:
Option 1: replace the single quotes with double quotes
If you choose this option, make sure that you either escape the existing double quotes, or change them into single quotes:
$sql = "SELECT column1, column2 FROM table WHERE date BETWEEN '$startdate' AND '$enddate' ORDER BY record_number DESC";
Option 2: concatenate the strings manually
You can also build op the query manually from multiple parts, and glue them together using PHP's concatenation operator, the dot (.).
$sql = 'SELECT column1, column2 FROM table WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate;
You should convert it to a greater than and less than equation:
date > '$startdate' AND date < '$enddate'
The issue isn't with your SQL, but with your PHP.
You need to read up on how string concatenation works and how PHP treats strings that use ' and " differently when wrapped around strings.
$sql = 'SELECT * FROM record WHERE date BETWEEN "$startdate" AND "$enddate"';
Should be changed to one of the following:
$sql = 'SELECT * FROM record WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate . '"';
OR:
$sql = "SELECT * FROM record WHERE date BETWEEN '$startdate' AND '$enddate'";
I've simplified the SQL to highlight the real issue at hand.

Mysql Get table result between two dates

I know my question is similar to other question already answered but my issue is different because I need some alternative or advice no how to go the other way around.
My issue is: I want to get values between either two dates or one according to what user wants..
When User request data of one day.. php query data successful.. but problem is when data requested is between two dates..
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '$first_date' AND
`meta_transaction_date` <= '$second_date' ");
return $query->result();
I get an empty set...
So I thought may be the values are not submitted correct.. so I echoed the values to see if they are correct or not. I find they are correct...
$first_date = 09/13/2014;
$second_date = 09/19/2014;
But if I try to put the value like
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014' AND
`meta_transaction_date` <= '09/19/2014' ");
return $query->result();
I get my result back correct.. so is there anything am doing it wrong??
Change the type of meta_transaction_date to DATE as that is what it is! Also use the standard 'yyyy-mm-dd' when passing in DATEs.
Your problem probably stems from string ordering of the 'mm/dd/yyyy' US date format which is horrible for coding. If you wish to display the DATE in this format, convert it when SELECTing the final output.
MySQL has a built in function called Between that you can use like this:
SELECT * FROM table_name WHERE date_column BETWEEN 'start_date_parameter' AND 'end_time_parameter'
Try to cast the date first , and then with between statement:
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` BETWEEN
date_format(str_to_date('$first_date', '%d/%m/%Y'), '%Y-%m-%d') AND
date_format(str_to_date('$second_date', '%d/%m/%Y'), '%Y-%m-%d')");
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014'
AND `meta_transaction_date` <= '09/19/2014' ");
Since the above seems to be working fine, the problem is in your code.
$query = $this->db->query("SELECT `meta_transaction_date` FROM meta_receipt_data WHERE
meta_transaction_date BETWEEN "
.date( "Y-M-d", ( strtotime($first_date) ) )." AND "
.date( "Y-M-d", ( strtotime($second_date) ) ) );
A word of advice, do not use queries like SELECT * as they will degrade performance of your application. And I just read in your comment to your own question:
I have set the type as Varchar
Do not do that. It is best to use the DATE type to store dates. You can use the query:
ALTER TABLE `meta_receipt_data`
MODIFY `meta_transaction_date` DATE NOT NULL;`
Well, that is assuming you wish to keep the column to not accept null values.
I found that the value had space before and after so I use $first = trim($first_date); and problem solved...

Python variables in other variables

I'm kind of new in python and want to make a MySQL select.
I want to select from the MySQL and add a variable to the query like this:
date = now.strftime("%Y-%m-%d)
sql = "SELECT * FROM table WHERE date='%s'" % date
(This offcourse, doesn't work)
I'm used to Php so this is kind of new to me as you can see :)
THANKS!
Maybe this does what you want...
date = now.strftime("%Y-%m-%d)
sql = "SELECT * FROM table WHERE date= '%s' "
sql = sql % (date)
cursor.execute(sql)
results = cursor.fetchall()
import time
now = time.localtime()
date = time.strftime("%Y-%m-%d")
sql = "SELECT * FROM table WHERE date='%s'" % date
I think this fragment does what you want?
Hope this helps

SELECT * BETWEEN AND

I'm trying to select a list of events from a database with MySQL. I'm fairly new to php but usually I can figure stuff out. cant seam to get this to work though..
function get_events_within_dates($da,$dd) {
global $connection;
$query = "SELECT *
FROM events
WHERE date
BETWEEN STR_TO_DATE('$da','Y-m-d') AND STR_TO_DATE('$dd','Y-m-d')
ORDER BY date ASC";
I've used $da and $dd as date of arrival and date of departure..
I can get it to work fine when I replace the variables with exact dates, tried messing around with STR_TO_DATE() and that didn't help either. Any help appreciated.
You are missing % in the format string. Use STR_TO_DATE() as:
STR_TO_DATE('$da','%Y-%m-%d')
Full query as below:
$query = "SELECT *
FROM events
WHERE date BETWEEN STR_TO_DATE('$da','%Y-%m-%d')
AND STR_TO_DATE('$dd','%Y-%m-%d')
ORDER BY date ASC";

Categories