1

Im going bananas in this error, when i submit form , can you help me out? thanks in advance

here's the 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 's perfect. Surround Yourself with English The absolute best way to learn ' at line 1

<?php 
include "base.php"; 

if(isset($_POST['submit'])){

      $post_title = $_POST['title'];
      $post_date = date('y-m-d');
      $post_author = $_POST['author'];
      $post_keywords = $_POST['keywords'];
      $post_content = $_POST['content'];
      $post_image= $_FILES['image']['name'];
      $image_tmp= $_FILES['image']['tmp_name'];


    if($post_title=='' or $post_author=='' or $post_keywords=='' or $post_content=='' or 

$post_image==''){

    echo "<script>alert('Any of the fields is empty')</script>";
    exit();
    }

    else {

     move_uploaded_file($image_tmp,"../images/$post_image");

      $insert_query = "insert into posts 

(post_title,post_date,post_author,post_image,post_keywords,post_content)  values 

('$post_title','$post_date','$post_author','$post_image','$post_keywords','$post_content')";



    if(mysql_query($insert_query)){

    echo "<script>alert('post published successfuly')</script>";
    echo "<script>window.open('view_posts.php','_self')</script>";

    }

else
      {
echo mysql_error();

   }



}


}
?>

<?php } ?>

3 Answers3

2

You are failing to properly escape the input data, so the ' in your data is being treated like an SQL special character.

This problem also renders you vulnerable to SQL injection attacks.

Stop using mysql_ — it is obsolete. Use a modern replacement that supports prepared statements which are the best way to deal with this issue.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The problem is with quotes.

Before building your SQL sentence, escape all the values with: mysql_real_escape_string().

BUT, please, please, please, use Mysqli's statements as a better option.

Oscar Pérez
  • 4,377
  • 1
  • 17
  • 36
  • 2
    I'm kind of leaning towards PDO now rather than mysqli - it seems to cause less issues once you get into the world of calling stored procedures. – CD001 Jan 27 '14 at 10:42
  • You're right @CD001 . I said `mysqli` because it is more similar to `mysql` extension, so the change is simplier. But your option is better. – Oscar Pérez Jan 27 '14 at 10:44
-2
insert_query = "insert into posts (post_title,post_date,post_author,post_image,post_keywords,post_content)  values 

('".$post_title."','".$post_date."','".$post_author."','".$post_image."','".$post_keywords."','".$post_content."')";
user3106988
  • 101
  • 1
  • 8