【发布时间】:2015-03-21 09:18:27
【问题描述】:
我正在使用 Xampp v3.2。
我正在尝试根据用户输入编辑、删除和更新数据库中的字段。但我收到一个错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Shezad, body = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecen' at line 128
我的代码只有 47 行。这是文档的主要 PHP 部分:
<div class="main">
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM `posts` WHERE id = ".$id;
$post = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$msg = "Post edited";
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$author = $_POST['author'];
$body = $_POST['body'];
$sql = "UPDATE `posts` SET title =".$title.", author =".$author.", body =" . $body . "WHERE id = " .$id;
$update_rows = $mysqli->query($sql);
echo "<p id=\"added\">" .$msg. "</p>";
}
?>
<?php if($post) : ?>
<?php while($row = $post->fetch_assoc()) : ?>
<form action="edit-post.php?id=<?php echo urlencode($id); ?>" method="POST">
<input type="text" name="title" value="<?php echo $row['title']; ?>" placeholder="Edit title of post...">
<input type="text" name="author" value="<?php echo $row['author']; ?>" placeholder="Edit author of post...">
<div class="clear"></div>
<textarea type="text" name="body" placeholder="Edit body of post..."><?php echo $row['body']; ?></textarea>
<input type="submit" name="submit" value="Edit Post...">
</form>
<?php endwhile; ?>
<?php endif; ?>
</div>
请帮帮我。谢谢!
也推荐其他代码问题
【问题讨论】:
-
见When to use single quotes, double quotes, backticks。
$title, $author等值必须用单引号引起来。 -
但这很容易受到当前形式的 SQL 注入的影响。建议切换到支持预准备语句的 API,例如 PDO 或 MySQLi,这样可以避免此问题,也可以避免使用现已弃用的
mysql_*()API。见How can I prevent SQL injection in PHP
标签: php mysql mysqli sql-insert mysql-error-1064