尝试将表单数据插入SQLite3时,Prepare语句不起作用

时间:2019-04-26 09:39:19

标签: php html pdo sqlite

因此,我试图通过HTML表单将数据插入SQLite数据库。我想使用准备好的语句,到目前为止,我已经做到了:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Title of the post:<br> <input type="text" name="title">
    <br>
    Post text:<br> <textarea name="body" rows="5" cols="50"></textarea>
    <br>
    <input type="submit" name="submit" value="Post!">

</form>


<?php

$user = $_SESSION['user'];
$title = $_POST['title'];
$body = $_POST['body'];

if(isset($_POST["submit"])){

try {
$conn = new PDO("sqlite:../ex1"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = $conn->prepare("INSERT INTO posts (user, title, body) VALUES ($user, ?, ?");

$q->bindParam(':title', $title);
$q->bindParam(':body', $body);


$q->execute($title, $body);


echo "done";

由于某种原因,这不起作用,但是此代码可以做到:

$user = $_SESSION['user'];
$title = $_POST['title'];
$body = $_POST['body'];

$sql = "insert into posts (user, title, body)
values ('" . $user . "', '" . $title . "', '" . $body . "');";
echo '<br>';

var_dump ($sql);

$conn->exec($sql);

这是为什么?如果可能的话,我想使用准备好的语句。

0 个答案:

没有答案