I'm new to coding with PHP, and in trying to create a to-do list I have come undone after creating a file called 'add.php' which is supposed to add new data to the table. The main file, index.php, calls the table elements ok and displays them on the browser, but I cannot add new items.
The code in add.php is here:
require_once 'app/init.php';
if(isset($_POST['name'])) {
$name = trim($POST['name']);
if(!empty($name)) {
$addedQuery = $db->prepare("
INSERT INTO items (name, user, done, created)
VALUES (:name, :user, 0, NOW() )
");
$addedQuery->execute([
'name' => $name,
'user' => $_SESSION['user_id']
]);
}
}
header('location: index.php');
?>
If it helps, I am using PHP 5.5.12 and MySQL 5.6.17, on WampServer 2.5
Answer
OK... and before anyone gets the misconception about being obligated to use the colon as a placeholder in the array, is a myth.
It is perfectly legal/valid syntax in PDO. (consult footnote).
The colon however, does need to be in the VALUES().
The real problem here is with this $POST
, and is missing its underscore for it $_POST
.
Error reporting would have thrown you an undefined variable notice.
Add error reporting to the top of your file(s) which will help find errors.
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure the session array is set/not empty, and that the session was started. That isn't shown/indicated in your post.
Also make sure that your form does use a POST method and that your input holds the name attribute for the input.
I.e.:
Check for errors in PDO also:
Your connection method is also unclear, so make sure you are indeed using PDO to connect with.
- Different MySQL APIs do not intermix.
Other references:
Footnote:
As stated in comments and being a nice find on the part of VolkerK:
"it is stored internally with the leading colon, see"
No comments:
Post a Comment