2017-02-20 9 views
0

複数の写真をアップロードしたり、写真の名前を変更したり、データベースのエントリを追加するためのスクリプトを作成しようとしました。データベースファイル名の入力は正しいですが、画像のアップロードファイル名はjpg名を合成しています。PHPファイルパスの命名の問題

ie。データベースのエントリは、ファイルを正しく命名されていますphoto_1、photo_2、photo_3

ファイルが間違って命名アップロードされています:photo_1.jpg、photo_1.jpgphoto_2.jpg、photo_1.jpgphoto_2.jpgphoto_3.jpg

未解決する方法がわからこれは私のデータベースのエントリとして正しいです。

<?php 
if (isset($_POST['submit'])) { 
    $j = 0; //Variable for indexing uploaded image 
    $image_post_id = $_POST["image_post_id"]; 

    $target_path = "uploads/"; //Declaring Path for uploaded images 
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array 




     $validextensions = array("jpeg", "jpg", "png", "JPG", "PNG", "JPEG"); //Extensions which are allowed 
     $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 

     $file_extension = end($ext); //store extensions in the variable 





     //MYSQL Handling 

      mysql_query("INSERT INTO post_images(`image_filename`, `image_post_id`) VALUES('0', '".addslashes($image_post_id)."')"); 
          $new_id = mysql_insert_id(); 

          $target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]);//set the target path with a new name of image 
          mysql_query("UPDATE post_images SET image_filename='post_".addslashes($new_id).".".strtolower($ext[count($ext) - 1])."' WHERE image_id='".addslashes($new_id)."'"); 












     $j = $j + 1;//increment the number of uploaded images according to the files in array  

     if (($_FILES["file"]["size"][$i] < 1000000) //Approx. 100kb files can be uploaded. 
       && in_array($file_extension, $validextensions)) { 
      if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder 
       echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; 
      } else {//if file was not moved. 
       echo $j. ').<span id="error">please try again!.</span><br/><br/>'; 
      } 
     } else {//if file size and file type was incorrect. 
      echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; 
     } 
    } 
} 
?> 
+0

あなたは今、何をしているか停止します、修正ちょうど=の右側に$target_pathを削除するには

。非難され、維持されておらず、安全でないデータベースAPIを使用しています。 PDOのような代替手段は、10年以上も利用可能です。 http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – miken32

+0

質問に答える人々を助けるために、私は2つのことを提案してもいいかもしれません。より読みやすくする。 2 - 結果として期待していることを教えてください(最終的な名前は、コードから取得しても、明示的であることが常に良い)。 –

答えて

1

あなたの問題は、あなたのforループでは、この行を次のとおりです。

$target_path = $target_path . "post_". $new_id . "." . strtolower($ext[count($ext) - 1]); 

このコード、本質的に明らかにあなたが望むものではない、「は以前の値に新しいファイル名を追加します」と言います。

$target_path = "post_". $new_id . "." . strtolower($ext[count($ext) - 1]); 
+0

ありがとう!魅力のように働いて、非常に感謝します。私はPHPで非常に熟練していません。私はmysqliに切り替える方法を理解する必要がありますね。 – Jason

+0

歓迎です.. ..!答えを受け入れてください:-) – BizzyBob