试图弄清楚如何将新帖子提交到已经使用mysql数据库中的数据条目创建的预先存在的表.我希望它测试请求是否首先来自POST,如果是,则将新行插入数据库并在表中显示新数据.这是我到目前为止所提出的,但在提交时,似乎没有任何事情发生,我的桌子就消失了.任何帮助是极大的赞赏.
这是我到目前为止所拥有的:
$result = MysqLi_query($dbconnect, $query);
$num_rows = MysqLi_num_rows($result);
}
if ($num_rows > 0) // build a table to show results
{
echo "<table border='1'>";
echo "<tr>";
echo "<th>Post ID </th>"; echo "<th>Author</th>";
echo "<th>Title</th>"; echo "<th>Post</th>";
echo "</tr>";
while($row = MysqLi_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['pid'] . "</td>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['post'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else{
echo "No rows returned.";
}
?>
<form name ="myForm" action ="second.PHP<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
method = "POST"> <br><br><br>
<h3> Create a Post </h3>
Author <input type ="text" size ="40" name ="author"/><br>
Title <input type ="text" size ="30" name ="title"/><br><br>
Post <br><textarea rows ="15" cols ="10" name ="post"></textarea><br>
<input type ="submit" name = "submitpost" value ="Submit Post"/>
</form>
<?PHP
// $sql = "INSERT INTO blog_posts (pid, author, title, post)
VALUES (NULL, '$_POST[author]', '$_POST[title]', '$_POST[post]')";
//if($_SERVER['REQUEST_METHOD'] === 'POST'){
//if(isset($_POST['submitpost'])){
//post the $sql back into the exisiting table somehow
?>
解决方法:
>请注意未来的读者.这个答案是基于OP的原始帖子. See the revisions.
将INSERT查询放在条件语句中:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['submitpost'])){
$sql = MysqLi_query($dbconnect, "INSERT INTO blog_posts (pid, author, title, post)
VALUES (NULL, '$_POST[author]', '$_POST[title]', '$_POST[post]')")
or die(MysqLi_error($dbconnect));
}
}
并更改action =“second.PHP<?PHP echo htmlspecialchars($_ SERVER ['PHP_SELF']);?>”只是动作=“”
对POST数组使用条件!empty()以确保不会获得任何空数据并可能抛出错误.
边注:
您现在的代码是SQL injection开放.使用mysqli
with prepared statements或PDO with prepared statements,它们更安全.
根据你的编辑,你错过了两个结束括号},如果使用它,error reporting会发出通知.
<form name ="myForm" action ="" method = "POST"> <br><br><br>
<h3> Create a Post </h3>
Author <input type ="text" size ="40" name ="author"/><br>
Title <input type ="text" size ="30" name ="title"/><br><br>
Post <br><textarea rows ="15" cols ="10" name ="post"></textarea><br>
<input type ="submit" name = "submitpost" value ="Submit Post"/>
</form>
<?PHP
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['submitpost'])){
$sql = "INSERT INTO blog_posts (pid, author, title, post)
VALUES (NULL, '$_POST[author]', '$_POST[title]', '$_POST[post]')";
$data = MysqLi_query($dbconnect, $sql)
or die(MysqLi_error($dbconnect));
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。