我是第一次尝试构建一个简单的表单来将数据插入MySQL表。但它无法正常工作。
这是表格:
<form action="" method="post">
Select Park : <select name="park_id">
<option value="">Select Park</option>
<?php foreach ($res as $row) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row['park_id'], $row['name']);
} ?>
</select>
Headline: <input type="text" name="headline">
<br>
Story: <input type="textbox" name="story">
<br>
Date: <input type="date" name="date">
Password :<input type="password" value="" name="password" id="password">
<input type="submit">
</form>
这是php:
if(isset($_POST['submit'])){
$stmt = $db->prepare("INSERT INTO tpf_newstest(headline,story,date,park_id) VALUES(:headline,:story,:date,:park_id)");
$stmt->execute(array(':headline' => $headline, ':story' => $story, ':date' => $date, ':park_id' => $park_id));
$affected_rows = $stmt->rowCount();
}
它都在同一个index.php文件中。关于我做错了什么的任何想法? 感谢
编辑:如果它有帮助这是整页
try
{
$pdo = new PDO('mysql:host=localhost;dbname=*', '*','******');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$output = 'Theme Park Database initialized';
$qry = "select park_id, name from tpf_parks order by name";
$res = $pdo->query($qry);
if(isset($_POST['submit'])){
$stmt = $db->prepare("INSERT INTO tpf_newstest(headline,story,date,park_id) VALUES(:headline,:story,:date,:park_id)");
$stmt->execute(array(':headline' => $headline, ':story' => $story, ':date' => $date, ':park_id' => $park_id));
$affected_rows = $stmt->rowCount();
}
?>
<form action="" method="post">
Select Park : <select name="park_id">
<option value="">Select Park</option>
<?php foreach ($res as $row) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row['park_id'], $row['name']);
} ?>
</select>
Headline: <input type="text" name="headline">
<br>
Story: <input type="textbox" name="story">
<br>
Date: <input type="date" name="date">
Password :<input type="password" value="" name="password" id="password">
<input type="submit">
</form>
答案 0 :(得分:2)
我认为问题是$ _POST中根本没有名为submit
的字段,因此不会执行插入代码。要解决此问题,您可以检查其他字段,例如submit
,park_id
等,而不是检查date
字段。
答案 1 :(得分:1)
提交时没有name
。那么if(isset($_POST['submit'])){
如何成为现实?您可以按如下方式调整html并尝试
<input type="submit" name="submit" value="Submit" />