将上传的图像的文件路径保存到MySQL数据库

时间:2013-05-21 02:53:23

标签: php mysql

我已经完成了无数不同的帮助菜单和主题,但仍然遇到问题。我只想将上传图像的文件路径插入MySQL数据库。我已经尝试将图像传递给变量,然后使用查询将其推送到数据库,但它无法正常工作。我的代码在下面,表单在顶部,php在下面:

<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 个答案:

答案 0 :(得分:0)

除了{p> Security issuesdeprecated extension之外,您需要做的就是将文件名插入数据库。为此,请在数据库中添加“filename”字段,然后相应地调整插入查询:

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

此外,您的$uploaddir变量为空,此刻文件可能甚至没有保存在任何地方。要正确移动文件,请尝试以下操作:

$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";
}

此脚本假定您信任上传的内容,而md5功能只是一种快速简便的方法来“清理”(如果我可以称之为)文件的名称。