当字段包含'字符时保存到MySQL时出错

时间:2012-12-17 15:13:29

标签: php mysql mysqli

我有一个PHP表单,它将变量保存到MySQL数据库中。该表单在VPS上运行,但是当在另一个VPS上尝试它时,当字段包含'字符时尝试写入数据库时​​会出错。因此,当字段包含'字符但不包含在另一个VPS上时,相同的PHP代码在1 VPS上工作。

这里有效:http://www.zoekmachineoptimalisatie.us/test.php 而这里(它是另一个VPS)它给出了一个错误:http://www.onzebruidsfotograaf.nl/test.php

我的表格:

<?php
$hostname = "localhost"; //host name
$dbname   = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn     = new MySQLi($hostname, $username, $password, $dbname);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked

    $title  = $_POST['updatetitle'];
    $bookid = 1;
    $update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;

    $conn->query($update) or die("Cannot update"); //update or error
}
?>


<?php
$bookid = 1;
$sql    = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>

<h2>Update Record <?php echo $bookid;?></h2>

<form action="" method="post">
    <?php

    while ($row = $result->fetch_assoc()) {
        ?>

        <textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>

        <table border="0" cellspacing="10">

            <tr>
                <td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
            </tr>
        </table>
        <?php
    }
    ?>
</form>

<?php
if ($update) { //if the update worked

    echo "<b>Update successful!</b>";

}
?>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

查询中未转义的引号会产生语法错误。不是完全自己构建SQL,而是使用准备语句为PHP变量使用SQL变量:

if (isset($_POST['Submit'])) { //if the submit button is clicked

    $title  = $_POST['updatetitle'];
    $bookid = 1;

    $update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
    $update->bind_param('sd', $title, $bookid);
    $update->execute();
}

您的一台服务器已启用Magic Quotes而另一台服务器未启用。 Magic Quotes现在被认为是不受欢迎的并且已被弃用,它会自动逃避输入。您应该关闭Magic Quotes并使用参数化查询/预处理语句 - 然后不需要转义任何内容,它会阻止SQL注入。

MySQLi和PDO API支持Paramterised查询。

答案 1 :(得分:0)

因为单引号会破坏查询语句。为了防止它或来自SQL Injection,您需要使用PDOMySQLI扩展名。有关更多信息,请参阅以下文章