问题描述
背景: 我浏览了有关此问题和解决方案的各种信息,但没有找到适合我的情况的信息。我知道我很可能会忽略难以置信的显而易见的事情,但这已经是几个小时了,我无法终生确定它是什么。我将按照本教程进行操作,但将其制作为我自己的课程:https://www.taniarascia.com/create-a-simple-database-app-connecting-to-mysql-with-php/。
发生了什么:当我单击“提交”按钮时,什么也没有发生。在页面加载时和单击“提交”后,我看到屏幕上显示“未设置”,所以我知道我在我的else块中,这意味着未设置$ _POST。
我希望发生的事情:我希望页面加载时看到“未设置”,但是一旦我填写了表单并单击“提交”,我希望在我的页面中看到“已设置” echo语句,表示我在if语句和isset($ _ POST ['submit'])中为true /成功,后跟“ Success”,表示try代码块已成功,加上在表单中输入的值字段出现在数据库中。不过,到目前为止,如果我能显示第一个“设置”,我会很高兴。
我尝试过:我尝试将php分解为一个单独的文件,并通过action =“ thatfile.php”将其链接到表单,但是得到的结果相同。我也尝试使用“ get”代替“ post”作为方法,并使用$ _REQUEST代替$ _POST,但是同样,同样的结果-显示“ not set”,数据库中没有数据。
这是我的代码:
<?php
if (isset($_POST['submit'])) {
require "../config.php";
echo "set";
try {
$connection = new PDO($dsn,$username,$password,$options);
$new_item = array(
"luggage" => $_POST['luggage'],"category" => $_POST['category'],"item" => $_POST['item'],"description" => $_POST['description']
);
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)","stuff",implode(",",array_keys($new_item)),":" . implode(",:",array_keys($new_item))
);
$statement = $connection->prepare($sql);
$statement->execute($new_item);
echo "Success";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "not set";
}
?>
<?php include "header.php"; ?>
<h1>Add An Item</h1>
<form method="post">
<label for="item">Luggage</label>
<input type="text" name="luggage" id="luggage"></form>
<label for="item">Category</label>
<input type="text" name="category" id="category"></form>
<label for="item">Item</label>
<input type="text" name="item" id="item"></form>
<label for="description">Description</label>
<input type="text" name="description" id="description">
<input type="submit" name="submit" value="submit">
</form>
<a href="index.php">Back to home</a>
<?php include "footer.php"; ?>
解决方法
您要在表单</form>
的最后结尾之前多次关闭表单</form>
,因此提交不在表单中。删除这些:
<label for="item">Luggage</label>
<input type="text" name="luggage" id="luggage"></form> ***HERE***
<label for="item">Category</label>
<input type="text" name="category" id="category"></form> ***HERE***
<label for="item">Item</label>
<input type="text" name="item" id="item"></form> ***HERE***