不发布到SQLite数据库

时间:2015-02-06 17:31:44

标签: php sqlite

如何让我的表单提交到我的SQLite数据库,我想我需要在某处添加一个INSERT INTO语句。在谈到PHP时,我有点愚蠢,有人可以解释为什么它不起作用并帮助我让它工作吗?

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
try {
    $dbh = new PDO('sqlite:mydb.sqlite3');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $dbh->exec("CREATE TABLE IF NOT EXISTS test (
             name VARCHAR(30),
             gender VARCHAR(30),
             age INTEGER)"
             );

    $data = array(
            array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
            );

    $insert = "INSERT INTO test (name, gender, age)
           VALUES (:name, :gender, :age)";
    $stmt = $dbh->prepare($insert);


foreach ($data as $m) {
    $name = $m['name'];
    $gender = $m['gender'];
    $age = $m['age'];
    $stmt->bindParam('name', $name);
    $stmt->bindParam('gender', $gender);
    $stmt->bindParam('age', $age);

    $stmt->execute();

}
    $result = $dbh->query('SELECT * FROM test');

    $dbh = null;

}
    catch(PDOException $e) {

    echo $e->getMessage();
}       

?> 

<div id="wrapper">

   <div class="banner1">
        <h2>Input</h2>
   </div>

<form id="form" method="post">
    Name:<br>
    <input type="text" name="name[0]"/> <br>
    Gender:<br>
    <input type="text" name="gender[0]"/> <br>
    Age:<br>
    <input type="number" name="age[0]" min="1" max="99"/> <br>

    <input id="submit" type="submit" value="Input">
    </form>

</div>

<div id="results">

    <div class="banner2">
            <h2>Results</h2>
    </div>

    <div class="data">
        <?php
            unset($_POST['submit']);
            $data=$_POST;

            foreach ($result as $row) {
            echo $row['name']  . " ";
            echo $row['gender'] . " " ;
            echo $row['age']  . "<br>" . " ";
            }

        ?> 
    </div>


</div>

</body>
</html>

这是一个截图,以便您可以掌握表单的概念以及我希望它如何工作。结果部分只是从数组生成,所以我可以看到输入的内容,但我喜欢输入表单将数据发送到我已创建/连接到上面的SQLite数据库。谢谢。 Screenshot of Form:

0 个答案:

没有答案