-5

This string works:

$sql = 'SELECT * FROM Bar_Info WHERE b_id=' .
    $db->real_escape_string($_GET['b_id']);

However, this one does not:

$sql = 'SELECT * FROM Bar_Info WHERE BarLink=' .
    $db->real_escape_string($_GET["BarLink"]);

b_id are variables and BarLink are names of bars some including hyphens. An example being: granite-city

Is there any reason the second example of code would not work?

halfer
  • 19,824
  • 17
  • 99
  • 186
TonyG
  • 5
  • 1

2 Answers2

1

You need to quote your SQL parameters:

$sql = 'SELECT * FROM Bar_Info WHERE BarLink=\'' . $db->real_escape_string($_GET["BarLink"]).'\'';

The first query likely works because you just use numbers, but the second one uses a string.

PS: Quoting is necessary in both cases as otherwise you are vulnerable to SQL injection.

MrTux
  • 32,350
  • 30
  • 109
  • 146
  • Ah yes, I knew it would be something simple. Thank you very much! – TonyG Apr 30 '15 at 15:11
  • @TonyG: don't forget to accept this answer, if it is the one you prefer. To do so, click the tick mark to the left, so it turns green. This is how we acknowledge assistance here (it is not mandatory but it is recommended). – halfer Apr 30 '15 at 15:40
  • 1
    @halfer: Yes thanks for pointing that out. I was going to as soon as I read it but I had to wait for the time limit. Thanks again MrTux – TonyG Apr 30 '15 at 15:48
  • Great stuff @TonyG. Also, whilst this code seems OK, bear in mind parameter binding is much better - this is supported by both PDO and MySQLi. – halfer Apr 30 '15 at 15:58
0

strings in SQL queries have to be surrounded by quotation marks, while integers don't. So if "BarLink" contains strings, you'll have to add those:

$sql = 'SELECT * FROM Bar_Info WHERE BarLink="' . $db->real_escape_string($_GET["BarLink"]).'"';
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50