I have made a simple php cms form with database but it does not work properly when I want to submit the form with some dummy data! I don\'t know why it happens & also I adde
You are missing a quote just before $post_image:
,$post_image'
Should be:
,'$post_image'
So the complete SQL statement becomes then:
$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')";
Please note that you are doing assignments in this if
:
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
You should be using double ==
instead of =
.
Finally, your code is vulnerable to SQL injection. So please use prepared statements with parameters.
Changes
empty
for check empty variable||
instead of or
move_uploaded_file
)$post_image'
) - This is the bug in your codemysqli_error
(if (!$insert_post){
)Code
<?php
if (isset($_POST['submit']))
{
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author))
{
echo '<script>alert("Some fields are missing")</script>';
}
else
{
if (!move_uploaded_file($image_tmp,"post_images/$post_image")) {
echo "Move Failed";
}
else
{
$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')";
$insert_post = mysqli_query($con,$insert_query);
if (!$insert_post){
echo mysqli_error($con);
}
else
{
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}
}
}
}
?>
writing if statement in this way is better
// this not always works
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}
// yeah much better
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author)){
echo '<script>alert("Some fields are missing")</script>';
}
and sql mistake most probably because of here
'$post_keywords','$post_content')";
$post_keywords
and $post_content
is null or empty