0

I'm having trouble reading apostropes from my MySQL database using PDO.

$pdo = new PDO('mysql:host=localhost;dbname=XXX', 'XXX', 'XXX');
$sql = "SELECT name, prod, id FROM api_data WHERE mname = '$url'";

    foreach ($pdo->query($sql) as $row) {
       $name = ($row['name']);
       $prod = ($row['prod']);
       $id = ($row['id']);
    }

Is there a workaround?

EDIT: Sorry! My Faul: $url contains the apostrophe.

  • 6
    Use a prepared statement instead. You should be doing that anyway. – Don't Panic Oct 05 '17 at 19:22
  • This sounds like an HTML output problem. Are you placing these values into HTML? You would need to use `htmlspecialchars()` on them, and `htmlspecialchars($value, ENT_QUOTES)` if you're using them inside HTML attributes. – Michael Berkowski Oct 05 '17 at 19:23
  • 1
    Separately though, if you have an input problem (more dangerous with apostrophes) the solution is to use `prepare()/execute()` with a `:url` placeholder. See [How can I prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for PDO examples. – Michael Berkowski Oct 05 '17 at 19:24
  • _it only reads it until the apostrophe._ - Where are you outputting? If you're outputting into an HTML element/attribute that uses single quotes you will terminate the input early. – waterloomatt Oct 05 '17 at 19:30

0 Answers0