2017-04-12 63 views
0

我有问题让PHP插入图像路径或目录到MySQL数据库。它只是存储图像名称,而不是图像的路径和名称。此外,我正在重命名图像以匹配存储在其下的项目标题(例如蓝色车标题,蓝色车图像名称)。而不是上传新的图像名称,它只存储原始图像名称。插入图像目录到MySQL

这是我的重命名并上传图像等:

// The directory that will recieve the uploaded file 
$dir = 'uploads/'; 

//variables for images 
$allowedExts = array("gif", "jpeg", "jpg", "png"); 
$temp = explode(".", $_FILES["picture"]["name"]); 
$extension = end($temp);   

if(isset($_POST['submit'])) { 
    if (strlen($title)>0 && strlen($description)>0) { 
      move_uploaded_file($_FILES['picture']['tmp_name'], $dir . "/" . $title ."." . $extension); 


      // Query database and insert data into item table 
      $itemQry = 'INSERT INTO items (title, picture, startPrice, category, description, quantity, location, sellingFormat, duration, paymentType, postageDetails) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 
      $statement = $conn->prepare($itemQry); 
      $statement->bind_param('sssssssssss', $title, $_FILES['picture']['name'], $startPrice, $category, $description, $quantity, $location, $sellingFormat, $duration, $paymentType, $postageDetails); 
      $statement->execute(); 
+0

*它只存储图像名称*因为这是你告诉它做的 –

+0

$ _FILES ['picture'] ['name']将只返回图像的名称(例如file.jpg) – Akintunde007

+0

如何我要改变这个吗? – Joel

回答

1

试试这个代码:

// The directory that will recieve the uploaded file 
$dir = 'uploads/'; 

//variables for images 
$allowedExts = array("gif", "jpeg", "jpg", "png"); 
$temp = explode(".", $_FILES["picture"]["name"]); 
$extension = end($temp);   

if(isset($_POST['submit'])) { 
    if ((strlen($title) > 0) && (strlen($description) > 0)) { 
     $newFilePath = $dir . "/" . $title . "." . $extension; 
     move_uploaded_file($_FILES['picture']['tmp_name'], $newFilePath); 

     // Query database and insert data into item table 
     $itemQry = 'INSERT INTO items 
      (title, picture, startPrice, category, description, 
      quantity, location, sellingFormat, duration, 
      paymentType, postageDetails) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 

     $statement = $conn->prepare($itemQry); 
     $statement->bind_param('sssssssssss', $title, $newFilePath, 
         $startPrice, $category, $description, 
         $quantity, $location, $sellingFormat, 
         $duration, $paymentType, $postageDetails); 

     $statement->execute(); 
    } 
} 

注:在这里,我已经使用$newFilePath作为一个新的变量,保持路径和新的文件名并使用相同的名称插入到数据库中。希望这可以帮助你:)。

+0

非常好,非常感谢你! – Joel

+0

很高兴它帮助! :)但是,从@Akin开始,“请不要仅仅使用扩展名来检查,而应该使用MIME类型代替,你拥有的东西很容易被欺骗”。照顾这些事情。 – prava