【问题标题】:PHP - Is It Possible To Insert Into Database The Session Name?PHP - 是否可以将会话名称插入数据库?
【发布时间】:2020-12-09 04:15:37
【问题描述】:

所以我正在用 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:\xampp\htdocs\bider\test2\new.php:52
Stack trace:
#0 C:\xampp\htdocs\bider\test2\new.php(52): PDOStatement-&gt;execute(Array)
#1 {main}
  thrown in <b>C:\xampp\htdocs\bider\test2\new.php</b> on line <b>52</b><br />

我猜它标记了“cesar”,因为那是会话名称。 有人可以帮忙吗?

【问题讨论】:

  • 是的,但为什么可以?
  • 可以,但它有什么用?
  • 这将用于当用户创建新帖子时,其用户名会保存到帖子数据库中,因此在显示帖子时,它会说明上传者:)
  • 无论如何,第二个查询是问题所在 - 您没有正确使用参数。将其与您的第一个进行比较并发现差异

标签: php mysql sql session session-variables


【解决方案1】:

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

这是一个可行的版本:

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

$statement2->execute(array(
  ":post_by" => $post_by)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多