我试图从表单插入数据库但是我一直收到错误 警告:mysqli :: query():空查询 我研究了这个,到目前为止我没有尝试过任何工作。
这是我的代码:
HTML表格
<form method="post" action="create.php">
<h2>Create a Project or Product</h2>
<h3>This is a</h3>
<select name="producttype">
<option value="Project">Project</option>
<option value="Product">Product</option>
</select>
<br>
<input type="text" name="topictitle" placeholder="Title"></input>
<br>
<textarea name="topicdescription" placeholder="Description"></textarea>
<textarea name="topiccontent" placeholder="Post" style="height:200px;"></textarea>
<br>
<input type="submit" value="Post" name="submit" style="width:200px;"></input>
</form>
PHP
<?php
include 'connect.php';
if(isset($_POST['submit'])){
$topicname = $_POST['topictitle'];
$topicdesc = $_POST['topicdescription'];
$topicsubject = $_POST['topiccontent'];
$type = $_POST['producttype'];
$timecreated = date('Y-d-m H:i:s',time());
$username = $_SESSION['username'];
$insert = "INSERT INTO topics (topic_subject,topic_description,topic_name,topic_type,topic_by,topic_date) VALUES ('$topicsubject','$topicdesc','$topicname','$type','$username','$timecreated')";
$createpage = mysqli_query($conn,$insert);
if ($conn->query($createpage) === TRUE) {
header('Location: project.php');
}else
{
}
}
?>
CONNECT.PHP看起来像这样(不包括属性)
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
我在网站的其他网页上使用了这种确切的方法,原因是某些原因无效。如果有人知道如何解决这个问题,我会非常感激。
由于
答案 0 :(得分:2)
为什么查询失败可能是空值的原因:
$insert = "INSERT INTO topics (topic_subject,topic_description,topic_name,topic_type,topic_by,topic_date) VALUES ('$topicsubject','$topicdesc','$topicname','$type','$username','$timecreated')";
if($createpage = mysqli_query($conn,$insert)){
# query was executed.
} else {
echo $insert, mysqli_error($conn);
}
此外,您对SQL注入负责,通过使用预准备语句来解决此问题:
$sql = "
INSERT INTO topics (
topic_subject,
topic_description,
topic_name,
topic_type,
topic_by,
topic_date
) VALUES (
?,?,?,?,?,?
)
";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "ssssss", $topicsubject, $topicdesc, $topicname, $type, $username, $timecreated);
if(mysqli_stmt_execute($stmt)){
header('Location: project.php');
die(); // make sure script exists directly.
} else {
die(mysqli_error($conn));
}
} else {
die("error in sql syntax: <pre>$sql</pre>");
}
始终在die()
之后使用exit()
或header('Location: ...')
,因为当用户位于其他页面时,服务器会愉快地继续执行脚本。此外,客户端可以忽略标头请求,从而使其成为潜在的安全风险。
答案 1 :(得分:0)
查询返回空值很可能是因为它没有从表单中获取任何内容。
$insert = "INSERT INTO topics (topic_subject,topic_description,topic_name,topic_type,topic_by,topic_date) VALUES ('$topicsubject','$topicdesc','$topicname','$type','$username','$timecreated')";
您是否尝试检查是否通过您正在使用的php变量访问表单中输入的值?
您正在通过他们的name
从HTML访问这些变量。
<input type="text" name="topictitle" placeholder="Title"></input>
尝试通过value