0

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

Hamza Shezad
  • 35
  • 1
  • 9
  • See [When to use single quotes, double quotes, backticks](http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks/11321508#11321508). The values `$title, $author` etc must be single-quoted. – Michael Berkowski Jan 22 '15 at 14:31
  • But this is vulnerable to SQL injection in its current form. It is recommended to switch to an API supporting prepared statements such as PDO or MySQLi, which avoids this issue, as well as avoids using the now deprecated `mysql_*()` API. See [How can I prevent SQL injection in PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Michael Berkowski Jan 22 '15 at 14:32

1 Answers1

0

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__);
John Conde
  • 217,595
  • 99
  • 455
  • 496