pdo mysql处理名称中的撇号(')

ruarlubt  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(296)

当我要查找的名字中有撇号时,我的pdo查询就会出现问题,比如 D'Angelo . 名称中没有(')的名称可以正常工作。

try {
    $dbh = new PDO("mysql:host=$host;dbname=$dbname",$config['DB_USERNAME'],$config['DB_PASSWORD']); 
    foreach($dbh->query("SELECT * from position WHERE spieler='$playername'") as $row) {
        echo ''.$row['pos'].'</td></tr>';
    }
    $dbh = null;
} 
catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

更新:
所以,在所有的帮助和提示下,我终于能够让这一切顺利进行。

$dbh = new PDO("mysql:host=$host;dbname=$dbname",$config['DB_USERNAME'],$config['DB_PASSWORD']);
                $stmt = $dbh->prepare("SELECT * from position WHERE spieler=:player1");
                $stmt->execute(array(":player1" => $player1));
                foreach ($stmt as $row) {
                echo ''.$row['pos'].'</td></tr>';
    }
    $dbh = null;
qcuzuvrc

qcuzuvrc1#

那是因为当你有一个名字 ' 在其中,您的查询如下所示:

"SELECT * from position WHERE spieler='D'Angelo'"

这是无效的,所以$dbh->query返回false,这是foreach的无效参数。要快速修复,您需要将查询从

"SELECT * from position WHERE spieler='$playername'"

"SELECT * from position WHERE spieler='" . addslashes($playername) . "'"

这会给你

"SELECT * from position WHERE spieler='D\'Angelo'"

正如已经指出的,你最好准备好陈述:

$stmt = $dbh->prepare("SELECT * from position WHERE spieler=:playername"
$stmt->execute(array(':playername' => $playername));
while ($row = $dbh->fetch_assoc()) {
    echo ''.$row['pos'].'</td></tr>';
}
sxissh06

sxissh062#

你应该用事先准备好的陈述。

$stmt = $dbh->prepare("SELECT * from position WHERE spieler= :playername")

if(isset($playername))
{
   $stmt->bindParam(":playername", $playername);
}

$stmt->execute();

相关问题