0

My question is, how do I get the name of the file I uploaded and store it into mysql. Here's my code:

define("UPLOAD_DIR", "../uploads/");

 if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"]['name'];

if ($myFile["error"] !== UPLOAD_ERR_OK) {
    echo "<p>An error occurred.</p>";
    exit;
}

// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
    $i++;
    $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}

// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
    UPLOAD_DIR . $name);
if (!$success) { 
    echo "<p>Unable to save file.</p>";
    exit;
}

// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);

And here's my sql query

$q= "INSERT INTO `discaction`(`posted_by`,`date_posted`,`date_happened`,`document`,`people_involved`,`reason`,`status`,`extra`) VALUES ('$posted_by','$date_posted','$_POST[monthreq]-$_POST[datereq]-$_POST[yearreq]','$name','$_POST[people_involved]','$_POST[reason]','$status','$extra')";

Thank you for your answers.

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
  • And what is your question here? What is the actual issue? You just posted code which is fine, but you did not ask a question. Most likely you have a problem here: `$_FILES["myFile"]`... – arkascha Feb 15 '14 at 08:49
  • Just use the `$name` variable. Does that not contain what you need? If not, why? – Amal Murali Feb 15 '14 at 08:49
  • $name contains the name of your file .. what else you are looking for ? – Abhik Chakraborty Feb 15 '14 at 08:49
  • it doesnt record to the mysql database and leaves the field blank, i will get confused if i want to check a file and i dont have the record in my database – user3262140 Feb 15 '14 at 08:50
  • and your query is vulnerable to sql injection, i hope you are aware – NullPoiиteя Feb 15 '14 at 08:51
  • 1
    As @NullPoiиteя said, you are **wide open** to SQL injection attacks, and you will be hacked if you haven't been already. Please use prepared / parameterized queries to prevent this from happening. See also: [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/) – Amal Murali Feb 15 '14 at 08:52
  • even if i use the $name to insert it into my sql database, it does not record. but all of the other field records – user3262140 Feb 15 '14 at 08:57

0 Answers0