0

EDIT Provided as requested is here how the Date column looks: Jan 15, 2014 Jan 16, 2014 Aug 10, 2014

So what i am trying to achieve, is extract every row that contains Jan 2014, so i get every row for that month in that year.

Here is my PHP code that generates the query:

    $monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE 'Date' LIKE " . "'{$monthYearString}'";
echo $query_current;

The echo gives me this query: SELECT * FROM table_name_here WHERE 'Date' LIKE 'Jan%2014'

Original question

I have a very weird issue here. If i perform a search using phpAdmin provided by my hosting site, and search for rows that are like a certain date, it conjures up this SQL statement, and it finds 3 rows:

SELECT * 
FROM  `table_name` 
WHERE  `Date` LIKE  'Jan%2014'

BUT, when I try to do the same thing either using SQL statements in phpAdmin or my own code, it shows NOTHING? How come? It is 100% the same statement. Really can't understand how I can search using the built-in phpAdmin function, and then it generates that SQL statement, and then when I try to inject it myself, it just returns 0 rows instead of 3.

Hope it makes sense.

Seerex
  • 591
  • 1
  • 9
  • 21

1 Answers1

2

The difference between single quotes and backticks is important here. You have quoted your column name instead of using backticks. It should be:

SELECT * FROM table_name_here WHERE `Date` LIKE 'Jan%2014'

The backtick character (see the Date column in the query above) allows you to indicate it's a name rather than a string. In this case, if you didn't have these, you would get an error because Date is a reserved word. The backtick allows you to use reserved words for table and column names.

Where as the single quote means it's a string. In the case of your query, you were essentially searching for any records where the string 'Date' contains the string 'January 2014' which isn't possible and will always return zero results.

For more information, check out this SO question: When to use single quotes, double quotes, and backticks in MySQL

Your code should look like this:

$monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE `Date` LIKE '{$monthYearString}'";
echo $query_current;
Community
  • 1
  • 1
Brendan Bullen
  • 11,607
  • 1
  • 31
  • 40
  • Wauw, thanks a LOT man. i was NEVER gonna get that on my own. Really really great answer, with good explanation and a link to further study + how to correct my code. I couldn't ask for more! Thanks a ton for both answering, and guiding me in the proper direction for more knowledge on the subject. – Seerex Jan 07 '14 at 16:04