Mediumorchid Coder Mediumorchid Coder - 1 year ago 28
HTML Question

HTML form not uploading to mysql

The data in the filled form are not uploaded to the database. If I remove the image column in the "insert into"-part and just write

$query = $db->prepare("INSERT INTO posts (author, title, text, date) VALUES(:author, :title, :text, NOW()))");

then it works, so there's probably an error. There are no error messages.


// post form

if (isset($_GET["action"])) {
if ($_GET["action"] == "create") {

echo "
<form action=\"index.php?page=blogposts&action=save\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"text\" name=\"title\" ><br>
<input type=\"text\" name=\"author\"><br>
<textarea name=\"text\"></textarea><br>
<input type=\"file\" name=\"image\" /><br>
<input type=\"submit\" value=\"Publish Post\">

} elseif ($_GET["action"] == "save") {

$imagepath = '' . $_FILES['image']['name'];

$author = htmlspecialchars($_POST["author"], ENT_QUOTES, "UTF-8");
$title = htmlspecialchars($_POST["title"], ENT_QUOTES, "UTF-8");
$text = htmlspecialchars($_POST["text"], ENT_QUOTES, "UTF-8");

if (!empty($author) && !empty($title) && !empty($text)) {
try {

$db = new PDO($dsn, $dbuser, $dbpass);
$query = $db->prepare(
"INSERT INTO posts (author, title, text, date, image) VALUES(:author, :title, :text, NOW()), $imagepath)");
$query->execute(array("author" => $author, "title" => $title, "text" => $text));
$db = null;


catch (PDOException $e) {
echo "There is an error.";

header('Location: index.php');

else {
echo "Error: Fill in all fields!<br/>";

else {
echo "Page not found";

I also have a part which check the uploaded image of errors, but I don't know where to add this.

if($_FILES['image']['error'] > 0){
die('An error ocurred when uploading.');

die('Please ensure you are uploading an image.');

// Check filetype
if($_FILES['image']['type'] != 'image/jpeg'){
die('Unsupported filetype uploaded.');

// Check filesize
if($_FILES['image']['size'] > 500000000){
die('File uploaded exceeds maximum upload size.');

// Check if the file exists
if(file_exists('uploads/' . $_FILES['image']['name'])){
die('File with that name already exists.');

// Upload file
if(!move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $_FILES['image']['name'])){
die('Error uploading file - check destination is writeable.');

Answer Source

You added an extra bracket just after NOW()). Also you need to bind the image column as well. When you add the variable directly into VALUES, you have eliminated and broken the use of prepared statements. Hence the need to bind the variable

$query = $db->prepare("INSERT INTO posts (author, title, text, date, image) VALUES(:author, :title, :text, NOW(), :imagepath)");
$query->execute(array("author" => $author, "title" => $title, "text" => $text,"imagepath" => $imagepath));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download