Php 如何使用PDO在数据库中插入数据?

Php 如何使用PDO在数据库中插入数据?,php,sql,Php,Sql,我的代码有错误吗?我试图插入文章,但没有插入 如果有人能检查我的代码并告诉我我的错误(我正在学习),那就太好了 家教的 附加条款 解释了您可能要检查的PDOStatement::bindValue。然后,您可能希望将代码更改为类似于此的内容,这可能会起作用: session_start(); include_once '../includes/connection.php'; if (isset($_SESSION['logged_in'])) { //display ad

我的代码有错误吗?我试图插入文章,但没有插入

如果有人能检查我的代码并告诉我我的错误(我正在学习),那就太好了


家教的

附加条款





解释了您可能要检查的
PDOStatement::bindValue
。然后,您可能希望将代码更改为类似于此的内容,这可能会起作用:

session_start();

include_once '../includes/connection.php';

if (isset($_SESSION['logged_in'])) {
    //display add page
    if (isset($_POST['title'], $_POST['content'])) {
        $title = $_POST['title'];
        $content = $_POST['content'];

        if (empty($title) or empty($content)) {
            $error = 'All fields are required';
        } else {
            $query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');

            $query->bindValue(1, $title, PDO::PARAM_STR);
            $query->bindValue(2, $content, PDO::PARAM_STR);
            $query->bindValue(3, time(), PDO::PARAM_INT);

            $query->execute();

            header('Location: index.php');
            exit();
        }
    }
}
编辑:

如果您只希望看到正在执行的查询,可以删除
If
s并对其进行测试,然后可以添加任何必要的
If
。也许,类似于:

session_start();

include_once '../includes/connection.php';

$title = $_POST['title'];
$content = $_POST['content'];
var_dump($title);
var_dump($content);
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
var_dump($query);
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();

你没有看到任何错误,因为你没有寻找它们。检查prepare()、bindValue()和execute()调用的返回值。并确保启用了error_reporting()。第一次输入:title to$title和content to$content
time()
返回一个整数。如果
PDO::PARAM_STR
是默认值,为什么要显式列出数据类型?始终
exit()
标题('Location:…')之后,一个简单的快捷方式是退出(标题('Location:…')尚未解决@阿德拉德利什么问题还没有解决?你能告诉我们你面临什么问题吗?你的期望也是什么?首先我是php新手,我正在练习向数据库中插入文章,以便稍后获取它,我正在编写此代码,因此没有插入文章,我不知道代码中的错误在哪里bcuz我在浏览器中没有看到任何错误!!
session_start();

include_once '../includes/connection.php';

$title = $_POST['title'];
$content = $_POST['content'];
var_dump($title);
var_dump($content);
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
var_dump($query);
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();