当我必须通过也使用引号的PHP语句放置包含引号的mySQL查询时,我遇到了麻烦,当我添加PHP变量时,这变得更加混乱。到目前为止,我提出的最好的是这样的:
$sqlQuery = 'SELECT document FROM `mentioned_places` WHERE name="'.$mentionedPlace.'";';
这真的只是一个引号的泥潭。有更简单的方法吗?
答案 0 :(得分:2)
答案 1 :(得分:2)
答案 2 :(得分:1)
您可以使用 double quotes :
$sqlQuery = "SELECT document FROM `mentioned_places` WHERE name='$mentionedPlace'";
但你最好使用prepared statements使用mysqli或PDO。
使用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();
使用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;
答案 3 :(得分:0)