1

I am trying to upload a file path into MySQL database. I have this html form:

<form action="" method="post" name="add_maps" enctype="multipart/form-data">
<table border="1" cellpadding="2" cellspacing="1" align="center" dir="rtl">
<tr>
<th>
name of map</th>
<td>
<input type="text" name="name_of_map"/>
</td>
<th>
select map</th>
<td>
<input type="file" name="file" id="file"/>
</td>
</tr>
<tr>
<input type="submit" name="submit_map" value="upload"/>
</tr>
</table>
</form>

And in the same page, I have the PHP code to upload:

<?php
require_once('../include/inner_global.php');
$hostdb = "localhost";
$namedb = "architect";
$userdb = "root";
$passdb = "root";
$id = $_REQUEST['id'];
$name='';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");

$path = "../uploads/".$_FILES['file']['name'];
if(isset($_POST['submit_map'])){
    try{
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
            $path = "./uploads/".$path;
            $sql = "INSERT INTO maps(name_of_maps, projects_id, map) VALUES (:name, :id, :file)";
            $stmt = $conn->prepare($sql);
            $stmt->bindValue(":name", $name);
            $stmt->bindValue(":id", $id);
            $stmt->bindValue(":file", $path);
            $count = $stmt->execute();
        }
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        header("location: insert_map_false.php?id=".$id);
    }
}
?>

When I go to the page where this html form is, I get directly this error in the header:

enter image description here

P.S

Files are uploaded correctly to their path, when i click on upload, but not added to database. EDIT

This is my table datatypes

enter image description here

am90
  • 201
  • 2
  • 11

2 Answers2

1

First check from post or not. Add all of your code inside this condition, it will solve your problem:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//All code ....
}

or create hidden input inside from:

<input type="text" name="id" type="hidden" value="<?php echo $_REQUEST['id']; ?>"/>

I think the problem is in $id = $_REQUEST['id']; because value of $id is empty after from submit

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20
1

Your sql query is:

    $sql = "INSERT INTO maps(name_of_maps, projects_id, map) VALUES (:name, :id, :file)";

But your column is name_of_map and not name_of_maps

You query should be like this:

$sql = "INSERT INTO maps(name_of_map, projects_id, map) VALUES (:name, :id, :file)";
alim1990
  • 4,656
  • 12
  • 67
  • 130