我正在设置自定义博客的基本提交系统。
这是我试图将插入的数据提交到数据库中的PHP部分
<?php
session_start();
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit();
}
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body)
VALUES($newTitle, $newPost)";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
?>
然后有提交表格,我很确定这是由于某种原因的错误结束,但我找不到原因。
<form action="<?php echo $_SERVER['PHP_SELF']?>"name="newTitle" method="post">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label><input type="submit" name="submit" value="submit"/>
</form>
这是数据库的表格:
post_id (A_I)
user_id
title
body
category_id
posted(datetime)
请记住,我是这个领域的新手,所以不要太苛刻:)
答案 0 :(得分:1)
对字符串使用单引号:
$sql="INSERT INTO posts (title, body) VALUES ('$newTitle', '$newPost')";
//^ ^ ^ ^
<强>注意:强>
尝试在项目中使用PDO
和param binding
来阻止sql注入。
答案 1 :(得分:0)
仅使用单一表格标签:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label>
<input type="submit" name="submit" value="submit"/>
</form>
在您的PHP代码中,您可以使用isset()函数检查您的数据
if(isset($_POST['submit'])){
if(isset($_POST['newTitle']) && ($_POST['newPost']))
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
$sql="INSERT INTO posts (title, body)
VALUES('$newTitle', '$newPost')"; //use variable in single quote.
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}