每次我提交我的网站表单进行评论时,它只会创建一个新的ID。但是所有其他值都是空的,我该怎么办?我是否需要为名称,电子邮件和内容创建一些属性?
<?php
error_reporting(E_ALL);ini_set('display_errors',1);
$servername = "localhost";
$username = "seamaszhou";
$password = "123456";
$dbname = "guest";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO guest
(guestName,guestEmail,guestContent)
VALUES (:guestName, :guestEmail, :guestContent)");
$stmt->bindParam(':guestName', $guestName);
$stmt->bindParam(':guestEmail', $guestEmail);
$stmt->bindParam(':guestContent', $guestContent);
// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();
?>
答案 0 :(得分:2)
这是错误的:
// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();
您尝试使用的变量不存在。您需要从$_POST
数组中检索表单发布的值:
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
编辑:请注意,即使表单未发布,您也会在每个请求上运行此代码。您需要添加一个检查:
if (isset($_POST['guestName']) && isset($_POST['guestContent']) && isset($_POST['guestEmail'])) {
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
}
实际上,您可能希望将与保存数据库中的数据有关的所有内容放在if
- 语句中,这样您就不会打开数据库连接或准备语句。 #39;不会使用它。