iTzMeRafa iTzMeRafa - 2 months ago 12
MySQL Question

save image / file information in a mysql database

I wrote this code to upload the informations of files in my mysql database:

<?php
require __DIR__ . '/database.php';

$file = $_GET["item"];

$itemName = $_GET["itemName"];
$uploadDate = filectime($file);
$filePathArray = pathinfo($file);
$filePath = $filePathArray["filename"];

$stmt = db()->prepare("INSERT INTO items (id, itemName, uploadDate, filePath) VALUES ('','{$itemName}','{$uploadDate}','{$filePath}");
$stmt->execute();
?>


Html code:

<form action="upload_action.php">
Item Name:<br>
<input type="text" name="itemName"><br>
File:<br>
<input type="file" name="item"><br>
<input type="submit" name="submit">
</form>


But I always get "filectime(): stat failed" and fatal error.. cant figure out why. Could you help me and correct my code, it would be a pleasure for me

Answer

You must add the enctype attribute to your form :

<form method="post" action="upload_action.php" enctype="multipart/form-data"> 
  Item Name:<br>
  <input type="text" name="itemName"><br>
   File:<br>
  <input type="file" name="item"><br>
  <input type="submit" name="submit">
</form>

Then your uploaded file will be in the global variable "$_FILES"

<?php
print_r($_POST);
print_r($_FILES);

$file = $_FILES["item"];

$itemName = $_POST["itemName"];
$uploadDate = filectime($file['tmp_name']);
$filePathArray = pathinfo($file['tmp_name']);
$filePath = $filePathArray["filename"];

print_r($uploadDate);
print_r($filePathArray);
?>

But before save the path in your DB, you should move the uploaded file with move_uploaded_file