2

I have gone through countless different help menus and topics for this and still having problems. I simply want to insert the filepath of an uploaded image into a MySQL database. I have tried passing the image on to a variable and then using a query to push that to the database but it is not working. My code is below, form is on top, php is below:

<html>

<body>

<h1>test</h1>

<form action="insert.php" method="post" enctype="multipart/form-data">

Name <input type="text" name="name" /><br><br>

Description <input type="text" name="desc" /><br><br>

Price Low<input type="text" name="price_low" /><br><br>

Price High <input type="text" name="price_high" /><br><br>

<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
3.Send this file: <input name="userfile" type="file" />
4.<input type="submit" value="Send File" /

<input type="submit" />

</form>
a

</body>
</html>




<html>

<?php
 //upload image
$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
//end of upload image


if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}



$con = mysql_connect("localhost","admintest","gen");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }



mysql_select_db("test2", $con);



$sql="INSERT INTO products (name, description, price_low, price_high)

VALUES

('$_POST[name]','$_POST[desc]','$_POST[price_low]','$_POST[price_high]')";



if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

echo "1 record added";



mysql_close($con)

?>



</body>

1 Answers1

0

Security issues and deprecated extension aside, all you need to do is insert the file name to the database. To do that, add a "filename" field to your database and then adjust your insert query accordingly:

INSERT INTO products (name, description, price_low, price_high, filename)
              VALUES (:name, :desc, :price_low, :price_high, :filename)

Also, your $uploaddir variable is empty, the files probably aren't even being saved anywhere at the moment. To move your files properly, try something like this:

$uploaddir = '/path/where/you/can/save/';
$rawFilename = $_FILES['userfile']['name'];
$extension = pathinfo($rawFilename, PATHINFO_EXTENSION);

$uploadfile = $uploaddir . md5($rawFilename) . '.' . $extension;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Upload failed";
}

This script assumes you trust the uploaded content and the md5 function is just is just a quick and easy way to "sanitize" (if I can call it that) the file's name.

Community
  • 1
  • 1
Pier-Luc Gendreau
  • 13,553
  • 4
  • 58
  • 69