0

I am trying to count logins by date range by counting how many times the auto integer (id) appears between a start and end date.

I get the start date and end date from a form in a previous page (y-m-d).

$start_date=$_POST['start_date']; /*in this case its "2014-10-10"*/
$end_date=$_POST['end_date']; /*in this case its "2014-10-20"*/


$sql = <<<SQL
SELECT id, COUNT(*) as login_count FROM `usage`  
GROUP BY id   
WHERE date
BETWEEN $start_date AND $end_date
SQL;

However I keep getting the following syntax error

"There was an error running the query [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE date BETWEEN 2014-10-10 AND 2014-10-20' at line 3]"

What am I doing wrong?

Almir M.
  • 76
  • 9
Dan
  • 9
  • 5

5 Answers5

1

your $sql should be :

$sql = <<<SQL
SELECT id, COUNT(*) as login_count FROM `usage`  
WHERE date
BETWEEN $start_date AND $end_date
GROUP BY id   
SQL;

as GROUP BY CLAUSE is AFTER WHERE syntactically

Satya
  • 8,693
  • 5
  • 34
  • 55
1

You need to put ''s around date literals in sql like so:

$response = mysql_query("SELECT * FROM `db`.`$sql_table` WHERE (date BETWEEN '$end_date' AND '$start_date')  ORDER by id ASC ")or die(mysql_error());
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • 1
    this does answer the question (apparently correctly), but it is more useful to to add a brief explanation of your answer. Just something like "You need to put quotes around date literals" would be enough. – Rhumborl Oct 20 '14 at 09:03
  • @Rhumborl, got it thanks. will do on my next answers. just new to stackoverflow. – Jeffrey Yee Oct 20 '14 at 09:10
1
try it 

$sql = <<<SQL
SELECT id, COUNT(*) as login_count FROM `usage`  
WHERE date
BETWEEN '$start_date' AND '$end_date'
GROUP BY id   
SQL;
Hara Prasad
  • 704
  • 6
  • 15
0

Firstly you should quote your dates '$start_date' AND '$end_date' and you should definitely make sure those values are escaped to avoid SQL injection.

Ukuser32
  • 2,147
  • 2
  • 22
  • 32
0

You have mistakes in your SQL. Try this:

SELECT id, COUNT(*) as login_count FROM `usage`  
WHERE (date BETWEEN $start_date AND $end_date)
GROUP BY id;
Alternatex
  • 1,505
  • 4
  • 24
  • 47