0

I'm having trouble putting together mySQL queries containing quotation marks when I have to put them through PHP statements that also use quotation marks, and this gets even messier when I add PHP variables. So far, the best I've come up with is something like this:

$sqlQuery = 'SELECT document FROM `mentioned_places` WHERE name="'.$mentionedPlace.'";'; 

Which is really just a quagmire of quotation marks. Is there a simpler way to do this?

Mike Causer
  • 8,196
  • 2
  • 43
  • 63
Jonathan
  • 10,571
  • 13
  • 67
  • 103

4 Answers4

2

Escape everything. If you are using mysql_ statements, stop using them as they are deprecated. Take a look at PDO or Mysqli.

Both of them escape symbols if you prepare the queries, so you also prevent sql injection.

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93
2

To secure your application you should use prepared statements with MySQLi or PDO.

Then you can separate your variables from your query and bind them to the statement.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
1

You can use double quotes:

$sqlQuery = "SELECT document FROM `mentioned_places` WHERE name='$mentionedPlace'"; 

But you're better off to use prepared statements either with mysqli or PDO.

Using mysqli:

$db = new mysqli(...);
$sql = "SELECT document FROM `mentioned_places` WHERE name = ?";
$query = $db->prepare($sql);
$query->bind_param("s", $mentionedPlace);
$query->execute();
$query->bind_result($document);
$documents = array();
while ($query->fetch()) {
    $documents[] = $document;
}
$db->close();

Using PDO:

try {
    $db = new PDO('mysql:host=localhost;dbname=test;charset=UTF8', 'user', 'userpwd');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $sql = "SELECT document FROM `mentioned_places` WHERE name = ?";
    $query = $db->prepare($sql);
    $query->execute(array($mentionedPlace));
    $documents = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Exeption: " .$e->getMessage(); //TODO better error handling
}
$query = null;
$db = null;
peterm
  • 91,357
  • 15
  • 148
  • 157
0

You can follow this procedure for give quotation for MYSQL query

Refer this Link and 2.links

Its more useful. Better you can use this link

Community
  • 1
  • 1
VIVEK-MDU
  • 2,483
  • 3
  • 36
  • 63