将文件路径存储在数据库中

时间:2014-10-23 05:20:46

标签: php

我想在数据库中存储文件路径。我尝试过这个。但它不起作用。这是我的代码。但它没有奏效。
    

 //This is the directory where images will be saved 
 $target = "uploads/"; 
 $target = $target . basename( $_FILES['photo']['name']); 

 //This gets all the other information from the form 
 $cat=$_POST['cat']; 
$desc=$_POST['desc'];

 // Connects to your Database 
 mysql_connect("localhost", "root", "") or die(mysql_error()) ;
 mysql_select_db("selfie") or die(mysql_error()) ; 

 //Writes the information to the database 
 mysql_query("INSERT INTO image_upload (category, description,image_url) VALUES ('$cat', '$desc',".$_FILES['photo']['name'].")"); 


 //Writes the photo to the server 
 if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
 { 

 //Tells you if its all ok 
 echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory"; 
 } 
 else { 

 //Gives and error if its not 
 echo "Sorry, there was a problem uploading your file."; 
 } 


?>

任何人都可以帮我在数据库中存储文件路径

2 个答案:

答案 0 :(得分:4)

您需要在文件名周围加上引号。您还应该转义所有用户提供的数据,以防它包含会导致SQL语法错误的特殊字符。

$filename = mysql_real_escape_string($_FILES['photo']['name']);
mysql_query("INSERT INTO image_upload (category, description,image_url, image_path) VALUES ('$cat', '$desc','$filename', '$target')"); 

答案 1 :(得分:0)

尝试改变这一点:

mysql_query('INSERT INTO image_upload (category, description,image_url) VALUES ("'.$cat.'", "'.$desc.'","'.$_FILES['photo']['name'].'");');

我假设您的$ cat和$ desc是字符串类型。