无法通过php上传文本值到mysql
每次我提交我的网站的评论表格时,它只会创建一个新的ID.But其他值是空的,我该怎么办?我是否需要为名称,电子邮件和内容创建一些属性? 无法通过php上传文本值到mysql
<?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();
?>
这是错误的:
// 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
语句来里面的数据库中保存的数据做的一切,让你不开数据库连接或准备一份声明,当你不打算使用它时。
谢谢你的帮助。我试图替换你给的代码。但网站跳了一些错误说: 注意:未定义索引:guestName在/var/www/htdocs/contact.php在线25 注意:未定义索引:guestContent在/var/www/htdocs/contact.php上第26行 注意:未定义索引:guestEmail在第27行的/var/www/htdocs/contact.php –
AND致命错误:未收到异常'PDOException',邮件为'SQLSTATE [23000]:完整性约束违规:1048'guestName'不能为null'in /var/www/htdocs/contact.php:28堆栈跟踪:#0 /var/www/htdocs/contact.php(28):PDOStatement-> execute()#1 {main}抛出/第28行的var/www/htdocs/contact.php –
这是因为您在每个请求上运行此代码,而不是仅在实际发布表单时。我已经更新了我的答案。 – rickdenhaan
你的HTML代码不应该是它的图像,它应该是实际的代码。请分别编辑你的文章。 –
你也发布了这个已经https://stackoverflow.com/questions/46744068/cant-upload-text-value-to-mysql和问题已被关闭为一个确切的副本。 –