我用数据库制作了一个简单的 php cms 表单,但是当我想提交带有一些虚拟数据的表单时它不能正常工作!我不知道为什么会这样,而且我还添加了 mysqli_error()
来获取我面临的错误类型,但我只得到了这个:
您的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册,了解在第 2 行的 '','','')' 附近使用的正确语法
<?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 ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}else{
move_uploaded_file($image_tmp,"post_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')";
$insert_post = mysqli_query($con,$insert_query);
if ($insert_post){
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}else{
echo mysqli_error($con);
}
}
}
?>
<form method="POST" action="" enctype="multipart/form-data">
<table width="600" align="center" border="10">
<tr>
<td align="center"><h6>Insert Post Title</h6></td>
<td align="center"><input type="text" name="title"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Author</h6></td>
<td align="center"><input type="text" name="author"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Keywords</h6></td>
<td align="center"><input type="text" name="keywords"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Image</h6></td>
<td align="center"><input type="file" name="image"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Content</h6></td>
<td align="center"><textarea name="content" cols="10" rows="10"></textarea></td></br>
</tr>
<tr>
<td align="center"><input type="submit" name="submit" value="Submit"/></td>
</tr>
</table>
</form>
如果您分享您对这个问题的解决方案,那将对我非常有帮助...谢谢!
最佳答案
您在 $post_image 之前缺少引号:
,$post_image'
应该是:
,'$post_image'
那么完整的SQL语句就变成了:
$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
中的作业:
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
您应该使用双 ==
而不是 =
。
最后,您的代码容易受到 SQL injection 的攻击.所以请使用prepared statements带参数。
关于php - php 形式的意外错误消息(SQL 语法错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967927/