不存在的行上的SQL语法错误

时间:2015-01-22 14:29:24

标签: php mysql mysqli sql-insert mysql-error-1064

我正在使用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>

请帮帮我。谢谢!

还建议其他代码问题

1 个答案:

答案 0 :(得分:0)

您有两个错误。您忘记将字符串值包装在引号中,并且在查询中的WHERE子句之前缺少空格。

$sql = $mysqli->query("UPDATE `posts` SET title ='".$title."', author ='".$author."', body ='" . $body . "' WHERE id = " .$id) or die($mysqli->error.__LINE__);