0

我第一次尝试构建一个简单的表单来将数据插入到 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>
4

2 回答 2

2

我认为问题是submit$_POST中根本没有命名字段,所以插入的代码不会被执行。要解决此问题,submit您可以检查其他字段,而不是检查字段,例如park_iddate等等。

希望有所帮助!

于 2013-08-10T14:09:42.097 回答
1

没有name提交。那么怎么可能if(isset($_POST['submit'])){变成真的呢?您可以如下调整html并尝试

<input type="submit" name="submit" value="Submit" />
于 2013-08-10T14:10:01.417 回答