0

I have a db table that contains some business names.

I need to query by name and usually have no problems unless the name contains an apostrophe.

("
SELECT*
FROM t1
WHERE bus_name = '".$busName."' 
")

I've experimented and tried using static value, like this:

("
SELECT*
FROM t1
WHERE bus_name = \"Bob's store\" 
")

and it worked. Tried:

("
SELECT*
FROM t1
WHERE bus_name = \"".$busName."\" 
")

and it doesn't. What am I missing?

Cœur
  • 37,241
  • 25
  • 195
  • 267
santa
  • 12,234
  • 49
  • 155
  • 255
  • 1
    Prepared statements and bound parameters? – andrewsi Nov 13 '15 at 16:17
  • 1
    You have to escape the content of the argument, not the quote chars. So either do it manually by using one of the escape functions offered by your php mysql extension, or, preferred, learn about the benefits of "prepared statements" and "parameter binding". – arkascha Nov 13 '15 at 16:20

2 Answers2

1

You should prepare the query, here is an example using PDO

$stmt = $pdo->prepare("
SELECT*
FROM t1
WHERE bus_name = :busName
");
$stmt->bindValue(':busName', $busName);
$stmt->execute();
var_dump($stmt->fetchAll());
meda
  • 45,103
  • 14
  • 92
  • 122
0

Use prepared statements for this ( or any ) case.

$pdo = new PDO(...);
$stmt = $pdo->prepare('SELECT ... FROM ... WHERE foo = :foo');

$stmt->bindValue(':foo', "foo ' bar");
$stmt->execute();

Your source at its current state is vulnerable against Command Injections ( SQL Injection ).

nihylum
  • 542
  • 3
  • 7