因此,我尝试将评论推送到我的数据库(icposts
,如下),但没有得到任何结果。我可以很好地提取并显示直接插入数据库表中的评论,但是当我尝试从 html 表单发送评论时,它似乎根本不起作用。
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
这是表单的 html,供引用:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
最佳答案
首先,您需要将连接传递给$database=mysqli_select_db("icposts");
。
然后您开始将 MySQL API 与 mysql_query
混合使用。它们只是不混合。
$database=mysqli_select_db($connect,"icposts");
那么你使用了错误的identifiers对于您的表格和列,是引号。
使用刻度线,或删除它们(引号)并将连接传递给查询:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
同时将 or die(mysqli_error($connection))
添加到 mysqli_query()
到 check for DB errors ,这就是您没有收到错误的原因;你没有检查他们。 Error reporting这是另一个你应该研究的。
示例:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
您还可以使用全部 4 个参数:
$connect=mysqli_connect("localhost", "root", "", "icposts");
您可能还想将 if($submit)
替换为
if(isset($_POST['submit']))
然后您可以删除$submit=$_POST['submit'];
。最好使用 isset()
。
注意:您需要确保您的currentDate
列允许空白数据,否则您需要为其提供某种形式的值。
关于“id”列的另一个注释。如果是 auto_increment,则可以在查询中省略它。
数据库会自行增加。
旁注:
您当前的代码已开放给 SQL injection 。使用prepared statements ,或PDO with prepared statements ,它们更安全。
在您开始使用准备好的语句之前,请使用以下命令更改代码:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
并对所有变量执行相同的操作。
这是准备好的语句入门:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
关于php - 将评论推送到本地主机上的我的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27280501/