PHP MySQL插入不起作用

时间:2015-10-29 14:36:43

标签: php mysql forms insert

我正在尝试将数据插入phpmyadmin。我对此有点新鲜。我试图用HTML表单插入数据。我有以下HTML代码:

<form id = "vraagStellen" action = "shoutbox.php" method = "post" class = "col-lg-12 col-md-12 col-sm-12 form-inline" role="form">
    <div class = "selectAfbeelding form-group">
        <label for "selectAfb">Naam:</label><br />
        <input type = "text" id = "selectAfb" name = "selectAfb" class = "form-control" maxlength="30"><br />
    </div>
    <div class = "selectVraag form-group">
        <label for "vraag">Bericht:</label><br />
        <input type = "text" id = "vraag" name = "vraag" class = "form-control" maxlength="100">
    </div>
    <br />
        <input type="reset" name = "reset" value = "Opnieuw" id = "reset">
        <input type="submit" name = "verzend" value = "Verzenden" id = "verzenden">
</form> 

PHP:

try {
    $conn = new PDO("mysql:host=".localhost.";dbname=".dbname, dbuser, dbpass);
} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}
$afbeelding = $_POST['selectAfb'];
$question = $_POST['vraag'];

$sql3 = "INSERT INTO `dbi286018`.`vraagstellen` (`id`, `Afbeelding`, `Vraag`, `date`) VALUES (NULL, :afbeelding, :question, CURRENT_TIMESTAMP);";
//Prepare your query
$stmt = $conn->prepare($sql3);
//Execute your query binding variables
$stmt->execute(array(':id'=>NULL, ':Afbeelding'=>$afbeelding, ':Vraag'=>$question));

2 个答案:

答案 0 :(得分:0)

如果你不想在db中插入值,你可以省略它。 您应该使用例如now()从mySQL db本身输入当前时间或date()函数或默认字段类型。

    $sql3 = "INSERT INTO `dbi286018`.`vraagstellen`
 (`Afbeelding`, `Vraag`, `date`) VALUES (:afbeelding, :question, now());";

占位符:问题/:afbeelding,必须匹配下面的绑定名称,并且必须将所有变量绑定到占位符:

  //Execute your query binding variables
    $stmt->execute(array(':Afbeelding'=>$afbeelding, ':question'=>$question));

我总是喜欢像下面这样构建make查询,它更容易阅读:

$sth = $dbh->prepare("INSERT INTO `dbi286018`.`vraagstellen`
   (`Afbeelding`, `Vraag`, `date`) VALUES (:afbeelding, :question, now()");

$sth->bindParam(':afbeelding', $afbeelding);
$sth->bindParam(':question', $question);
$sth->execute();

答案 1 :(得分:0)

除了我的评论,你在查询中混合了vraag和问题(见最后一行)。

$sql3 = "INSERT INTO `dbi286018`.`vraagstellen` (`id`, `Afbeelding`, `Vraag`, `date`) VALUES (NULL, :afbeelding, :question, CURRENT_TIMESTAMP);";
//Prepare your query
$stmt = $conn->prepare($sql3);
//Execute your query binding variables
$stmt->execute(array(':id'=>NULL, ':Afbeelding'=>$afbeelding, ':question'=>$question));