I am having a bit of trouble writing a mysqli query that queries between dates.
The column in my mysql database is a datetime column.
The query I have written in php looks like this
$sessions = mysqli_query($db,"SELECT s.idSession, s.idUser,
FROM rempad.Session AS s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
I have tried escaping the dates like \'2013-04-28\'
I have also tried casting as datetime like: DATETIME(s.start) BETWEEN DATETIME('2013-04-28') AND ...
But that doesn't work.
I have tested the SQL syntax in Mysql workbench so I know that the query returns values, but I can't seem to get it right in php.
Any ideas? I can't find any examples online.
Thanks in advance
L
I tried it and it worked as:
query($db,"SELECT s.idSession, s.idUser
FROM rempad.Session s WHERE s.idUser = 12 AND s.start BETWEEN '2013-04-28' AND '2013-05-28'");
Removed a comma and 'as' after table name.
Related
I'm trying to perform a query in Laravel 7 that gets the month part of a date field. I tried the following queries
$test = MyModal::selectRaw('month("date_col") as temp')->get();
$test = MyModal::select(DB::Raw('month("date_col") as temp'))->get();
$test = DB::table('my_table')->select('month("date_col") as temp')->get();
All variation of the same query. If I dump the query log, the query is correct for all 3
select month("date_col") as temp from "my_table"
If I run this on my DB I get the result as well. But I keep getting this error in laravel:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such function: month (SQL: select month("date_col") as temp from "my_table")
Am I doing something wrong? And is there a way to do this query in laravel?
Edit: Sorry forgot to mention this is with Laravel's unit testing
I think the problem in the way you use Month function
you don't set quotations for the column name, it should be:
$test = MyModal::selectRaw('month(date_col) as temp')->get();
it should work
You can do something like this:
MyModal::select(DB::raw("MONTH(date_col) month"))->get();
Thanks to OMR's comment this solution finally worked
$test = MyModel::selectRaw('strftime("%m", "date_col") as temp')->get();
Update: It looks like what I had in the beginning worked fine and the unit test was the only part throwing this error. Since I was working with mysql while the test environment was using sqlite which apparently doesnt like the "month()" function which OMR did point out in his comment. So this solution works in the test but not in live. Couldn't figure out how to change the test environment to use in memory mysql instead of sqlite. If anyone knows how to please add an answer here.
been googling for hours and I'm quite new to this.
I have two identical tables in one MySQL database:
One named "users" and one named "keys".
They are identical for testing purposes.
When I query "users" I get a response, when I query "keys" I get nothing.
Querying users I get the expected response:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM users
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Querying keys I get nothing:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM keys
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
I guess there must be some basic understanding of databases that has slipped by me, but still, after hours of searching I can't figure it out. Maybe I'm becoming retarded.
I think that might be due to table name being 'keys'.
Have a look here:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You have to understand while designing your tables and naming the attributes that some words are reserved by MySQL itself.
So, if you name your table 'WHERE' you will have troubles in usual query. Why?
'SELECT * FROM WHERE'
Such a query obviously doesn't work, as it will ask you to provide table name.
Now, when you change format situation also changes:
'SELECT * FROM `WHERE`'
As you can see I added some backwards commas. In MySQL they are used to denote names of tables or fields. If you use them - the server processes and reads your query correctly.
So, that's why your edited query worked fine in the end.
Thanks to enabeling debugging, I got this message:
mysql_result() expects parameter 1 to be resource, boolean given in
...
And figured out that I had to query "keys" like this:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT `name`
FROM `keys`
WHERE `can_share` = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Now it works, but I still don't understand why only one of the tables needed that formatting. And I have learned that I should rewrite the whole thing to not be vulnerable to SQL injection attacks. ...
EDIT: It seems like the words "key" and "keys" and some more are reserved by MySQL, so to use them, they have to be formatted like that.
I have a problem with executing ODBC query. I am trying to achieve something simple.
SELECT t.* FROM table t WHERE DateTime > '#2014-05-05 00:00:00#'
I have tried to execute with or without hashes (#) and quotes around the datetime, but no success with that. Also, instead of using >, < and other comparison operators I have tried to use BETWEEN.
In addition several formats "dd/mm/yyyy", "mm/dd/yyyy", "dd.mm.yyyy", etc. plus standard sql format (iso) were tested and the result is the same.
The approach looks like:
$sql = "SELECT t.* FROM table t WHERE DateTime > '#...#'";
$result = odbc_fetch_array(odbc_exec($odbc_connection, $sql));
After this execution I receive some 5-10 symbol binary error, but no error message (with odb_error and odbc_errormsg), in addition to the:
No tuples available at this result index
(The topic: ODBC error in PHP: “No tuples available at this result index” is not helping)
Could it be some ODBC issue (old version etc.) or we should cast another black magic through odbc_exec?
Maybe ODBC have trouble with reserved word datetime.
I don't know how to escape quotes in PHP, try
SELECT t.* FROM table t WHERE t."DateTime" > '20140505'";
You should use ODBC syntax for datetimes which is { ts '1998-05-02 01:23:56.123' }. You can omit the partial seconds. See here.
Have you tried using the TO_DATE() function? You can specify the format you are using.
SELECT t.* FROM table t WHERE DateTime > TO_DATE('2014-05-05 00:00:00','YYYY-MM-DD HH24:MI:SS')
This question may be in part a duplicate of How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?, but I could not get any of the answers there working in my code. We're using MySQL 5.0.95, I don't know if that makes a difference, but I couldn't find a definitive answer that solved my problem.
Here's my code:
public function getZipCodes() {
// get records
$select = new Zend_Db_Select($this->db);
$select->from('postal_codes AS p', array(
'p.postal_code',
'p.city',
'p.county',
'p.area_codes',
's.rate',
// convert from datetime to mm/dd/yyyy format <== problem here
'CONVERT(varchar(11), s.date, 101)'))
->joinInner('sales_surtax_rates AS s', 'p.county = s.county', array())
->where('p.state = "FL"')
->order('p.postal_code');
$zip_codes = $this->db->fetchAll($select);
Zend_Debug::dump($zip_codes);
die();
}
I get a syntax error when trying to convert the datetime to a formatted string. I'm just not seeing what I'm missing, and other methods like FORMAT and cast didn't work for me either.
I'm well aware I can just loop through and reformat the datetime via PHP for each array item after pulling the records from the database, but I'm just trying to avoid the extra step(s) if I can and learn something new in the process.
You're using MSSQL syntax, it would appear, NOT MySQL's.
Try
DATE_FORMAT(s.date, '%m/%d/%Y')
instead.
Relevant docs: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
I am unable to get the following code to work:
// dd/mm/yyyy for dates in SQL queries
$todayforw = date('d/m/Y');
$aweekago = date('d/m/Y', time() - 604800);
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'");
while ($week_e_info = mysql_fetch_array($week_e_check)) {
$week_e = $week_e + $week_e_info['user_earnings_amnt'];
}
The query returns zero rows, however, it should be returning data that matches the criteria.
Check your date format:
Should be:
YYYY-mm-dd HH:mm:ss
E.G.
2012-01-01 00:00:00 (January 1, 2012 at midnight local time)
Other date formats MAY work, but the best way to go about it is to use the same format that MySQL uses when they display the date, that's the only way I know that works every time.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Also your syntax is incorrect, you have two wheres, you should use AND.
Take a closer look at your query:
SELECT * FROM earningslog WHERE user_id = '".$info['id']."' WHERE day >='".$aweekago."' AND day <'".$todayforw."'"
Your Where clause appears twice.
Two things to think about - when you are selecting data, try and stay away from select * - you may get unexpected results of the table is ever modified.
Second, try and create the query as a parameterized query, instead of injecting the parameters directly into the where clause. By directly injecting your criteria the way you have, you are opening yourself up to a SQL injection attack.
By turning it into a parameterized query, you get the side benefit of being able to debug the queries directly against the database, reducing the amount of effort needed to copy it from a query tool into your code.
Your issue appears to be with your query syntax. You are stating WHERE twice, whereas you should only state it once and then use the AND or OR operators for further criteria. I would also suggest that you either move your statement into a variable or use die() to assist with debugging.
$week_e_check = mysql_query("SELECT * FROM earningslog WHERE user_id = '".$info['id']."' AND day >='".$aweekago."' AND day <'".$todayforw."'") or die(mysql_error());
In addition, you should not be using the mysql extension as use of this extension is discouraged. Instead, use the MySQLi or PDO_MySQL extension. Using one of these alternative extensions will help serve as the first step in preventing SQL injection. I would also suggest that you avoid using * and specify the column names to be returned instead.
Using PDO:
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT * FROM earningslog WHERE user_id = ? AND day >= ? AND day < ?');
$sth->execute(array($info['id'], $aweekago, $todayforw));
$results = $sth->fetchAll();
?>
Try change the format of your strings from from d/m/Y to Y-m-d.
MySQL might be expecting it year first. In which case it could be doing the wrong thing with d/m/Y.
Also don't use the WHERE clause twice. Instead, combine conditions using AND, eg:
WHERE user_id = '".$info['id']."'
AND day >='".$aweekago."'
AND day <'".$todayforw."'
By the way, you can also try saying WHERE day BETWEEN ".$aweekago." AND ".$todayforw.", which might be easier syntax to read (as long as you change $todayforw to be the day before).