PHP-可以在数据库中插入会话名称吗



所以我正在用PHP制作一个发布系统。当用户想要创建一个帖子时,所有的字段都需要完整,我试图做的是将会话的名称插入数据库,例如,插入数据库"Edward",因为这将是会话的名称。以下是我要做的:

<?php
session_set_cookie_params(86400*30, "/");
session_start();
require 'admin/config.php';
require 'functions.php';
if (isset($_SESSION['user'])) {
require 'view/new.view.php';
} else {
header('Location: index.php');
}
$connection = connect($bd_config);
if (!$connection) {
header('Location: error.php');
}
$errors = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = cleanData($_POST['title']);
$demo = cleanData($_POST['demo']);
@$project_type = $_POST['project_type'];
$content = $_POST['content'];
$post_by = $_SESSION['user'];
$errors = '';
if (empty($title) or empty($demo) or empty($project_type) or empty($content)) {
$errors .= '<p>Complete all the fields!</p>';
} else {
$statement = $connection->prepare("
INSERT INTO posts (ID, title, demo, content, post_type)
VALUES (null, :title, :demo, :content, :project_type)
");
$statement->execute(array(
':title' => $title,
':demo' => $demo,
':project_type' => $project_type,
':content' => $content,
));
$statement2 = $connection->prepare("
INSERT INTO posts (post_by)
VALUES ($post_by)
");
$statement2->execute(array(
$post_by
));
header('Location: main.php');
}   
}
?>

正如您所看到的,我正在为2个SQL查询执行2个statement变量,但当我这样做时,它会抛出以下错误:

<b>Fatal error</b>:  Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cesar' in 'field list' in C:xampphtdocsbidertest2new.php:52
Stack trace:
#0 C:xampphtdocsbidertest2new.php(52): PDOStatement-&gt;execute(Array)
#1 {main}
thrown in <b>C:xampphtdocsbidertest2new.php</b> on line <b>52</b><br />

它标记为"cesar",因为我想这是会话名称。有人能帮忙吗?

您的第二个查询是问题所在-您没有正确使用参数。将它与你的第一个进行比较,找出结构上的差异。您需要在INSERT语句中指定一个占位符:post_by,以便PDO知道在哪里绑定变量,并且您需要为参数数组中的$post_by条目指定与索引相同的名称,以便它们匹配。

这是一个有效的版本:

$statement2 = $connection->prepare(
"INSERT INTO posts (post_by) 
VALUES (:post_by)"
);
$statement2->execute(array(
":post_by" => $post_by)
);

最新更新