无法通过php将文本值上传到mysql
每次我提交网站表单以进行评论时,它只会创建一个新ID.但是所有其他值均为空,我该怎么办?我需要为名称,电子邮件和内容创建一些属性吗?
Every time I submit the form of my website for comment, It only creates a new ID.But all other value is empty, what should I do? Do I need create some attribute for the name, email and content?
<?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();
?>
HTML代码:
这是错误的:
// insert a row
$guestName = "$guestName";
$guestContent = "$guestContent";
$guestEmail = "$guestEmail";
$stmt->execute();
您要使用的变量不存在.您需要从$_POST
数组中检索表单发布的值:
The variables you're trying to use don't exist. You need to retrieve the values posted by the form from the $_POST
array:
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
编辑:请注意,即使没有发布表单,您也会在每个请求上运行此代码.您将需要为此添加支票:
Note that you are running this code on every request, even if the form is not posted. You will want to add a check for that:
if (isset($_POST['guestName']) && isset($_POST['guestContent']) && isset($_POST['guestEmail'])) {
$guestName = $_POST['guestName'];
$guestContent = $_POST['guestContent'];
$guestEmail = $_POST['guestEmail'];
$stmt->execute();
}
实际上,您可能希望将与将数据保存在数据库中有关的所有内容都放在该if
语句中,以便在不使用数据库时不打开数据库连接或准备语句使用它.
Actually, you might want to put everything that has to do with saving the data in the database inside that if
-statement, so that you're not opening a database connection or preparing a statement when you're not going to use it.