我看到了类似的话题,但是在尝试了一些上述解决方案后,我仍然没有找到正确的答案。我对MySQL和PHP还是很陌生,我很确定在某个地方看不到一个小错误,但是几天来我一直在努力解决这个问题,所以我决定问一下。
问题是,当我创建一个html表单和方法以将表单中的值插入数据库时,我获得了“成功”的插入,但是仍然向数据库中添加的所有行都是空的。
HTML表单:
<div class="panel panel-default">
<div class="panel-body">
<form action="InsertMessage.php" method="post">
<div class="form-group">
<label for="comment">First name:</label>
<textarea class="form-control" id="comment" name=first_name rows="1" required></textarea>
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="date">Date:</label>
<input type="date" class="form-control" name="desired_date" id="desired_date" required>
</div>
<div class="form-group">
<label for="time">Time:</label>
<input type="time" class="form-control" name="desired_time" id="desired_time" required>
</div>
<div class="form-group">
<label for="comment">Comment</label>
<textarea class="form-control" id="comment" name="info" rows="3" placeholder="placeholder" required></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
PHP代码:
$host = "localhost";
$username = "root";
$password = "";
$database = "name";
//create a connection
$conn = new mysqli($host, $username, $password, $database);
$first_name = filter_input(INPUT_POST, 'first_name');
$email = filter_input(INPUT_POST, 'email');
$desired_date = filter_input(INPUT_POST, 'desired_date');
$desired_time = filter_input(INPUT_POST, 'desired_time');
$info = filter_input(INPUT_POST, 'info');
if(mysqli_connect_error()){
die('Connection error (' . mysqli_connect_errno() . ')' .
mysqli_connect_error());
}else{
$sql = "INSERT INTO messages (first_name, email, desired_date,
desired_time, info) VALUES
('$first_name','$email','$desired_date','$desired_time','$info')";
if ($conn->query($sql)){
echo "New record is inserted successfully!";
}
else{
echo "Error:" . $sql . $conn->error;
}
$conn->close();
}
答案 0 :(得分:0)
尝试一下
$host = "localhost";
$username = "root";
$password = "";
$database = "name";
//创建连接
$conn = new mysqli($host, $username, $password, $database);
$first_name = $_POST['first_name'];
$email = $_POST['email'];
$desired_date = $_POST['desired_date'];
$desired_time = $_POST['desired_time'];
$info = $_POST['info'];
if(mysqli_connect_error()){
die('Connection error (' . mysqli_connect_errno() . ')' .mysqli_connect_error());
}else{
$sql = "INSERT INTO messages set `first_name`='$first_name', email='$email', desired_date='$desired_date',desired_time='$desired_time', info='$info' ";
if ($conn->query($sql)){
echo "New record is inserted successfully!";
}
else{
echo "Error:" . $sql . $conn->error;
}
$conn->close();
}