Reputation:
So I'm making a posting system with PHP. When the user wants to create a post, all the fields need to be complete, and what I'm trying to do is to insert into the database the name of the session, for example, to insert to the database 'Edward', because that would be the name of the session. Here's what I'm trying to do:
<?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');
}
}
?>
As you can see, I'm doing 2 statement
variables for 2 SQL consults, but when I do that, it throws this error:
<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->execute(Array)
#1 {main}
thrown in <b>C:\xampp\htdocs\bider\test2\new.php</b> on line <b>52</b><br />
It marks 'cesar' cause that's the session name, I guess. Can someone help?
Upvotes: 0
Views: 152
Reputation: 61849
Your second query is the problem - you're not using parameters properly. Compare it to your first one and spot the difference in the structure. You need to specify a placeholder :post_by
in the INSERT statement so PDO knows where to bind the variable, and you need to give the $post_by
entry in the parameter array the same name as an index, so they match up.
Here's a version which will work:
$statement2 = $connection->prepare(
"INSERT INTO posts (post_by)
VALUES (:post_by)"
);
$statement2->execute(array(
":post_by" => $post_by)
);
Upvotes: 1