Search code examples
phpmysqlmysqlisql-insertmysql-error-1064

SQL Syntax Error on a Line which doesn't Exist


I am using Xampp v3.2.

I am trying to edit, delete and update fields in the database according to the user input. But I'm getting an error:

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

My code has 47 lines only. Here is the main PHP part of the document:

<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>

Help me, please. Thank You!

Also recommend other code problems


Solution

  • You have two errors. You forgot to wrap your string values in quotes and you are missing a space before theWHERE clause in your query.

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