简体   繁体   中英

quotation marks in PHP and mySQL

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?

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.

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM