2017-07-15 53 views
0

我有一個表格,其中每個輸入包含在數組。該數組包含文本輸入和文件輸入。如果這已經是一個巨大的紅旗,那麼TLDR - 可以將包含文本和文件輸入的數組傳遞給用於數據庫上傳的相同SQL語句嗎?PHP:數組可以包含文本和文件輸入嗎?

我在我的PHP中有一個echo聲明,我嘗試回顯輸入名稱,「段落」和「圖像」。 「段落」是文本輸入,「圖像」是文件輸入。

foreach($_POST['items'] as $index => $item){ 

    $key = key($item); 
    echo $key; 
    .... 

^這個回聲「段落」,但不回聲「圖像」。

對於有點更清晰,這裏是形式:

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

    <textarea name="title"></textarea> 

    <!--paragraph input--> 
    <div><textarea name="items[][paragraph]"></textarea></div> 
    <!--paragraph input--> 
    <div><textarea name="items[][paragraph]"></textarea></div> 
    <!--paragraph input--> 
    <div><textarea name="items[][paragraph]"></textarea></div> 
    <!--file input--> 
    <div><input type="file" name="items[][image]" id="uploadImage" multiple></div> 
    <!--file input--> 
    <div><input type="file" name="items[][image]" id="uploadImage" multiple></div> 
    <!--file input--> 
    <div><input type="file" name="items[][image]" id="uploadImage" multiple></div> 

    <input type="submit" name="upload" value="Upload" id="upload"> 

</form> 

...和PHP。沒有處理文件類型並將其存儲在目錄中,因爲我只是想知道是否有可能讓foreach識別文件輸入。

<?php 

    if (isset($_POST['upload'])) { 

    $host = ""; 
    $dbname = ""; 
    $user = ""; 
    $pass = ""; 

    try {  
     $db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
     $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

     $statement = $db->prepare("INSERT INTO table (placement, datatype, typetext) VALUES (:placement, :datatype, :typetext)"); 

     if($statement){ 

      if(is_array($_POST['items'])){ 

       foreach($_POST['items'] as $index => $item){ 

        //this is where I'm trying to catch the names of 
        //the inputs, "paragraph" and "image". This will 
        // print "paragraph", but will NOT print "image" 

        $key = key($item); 
        echo $key; 

        $statement->execute(['placement' => $index, 'datatype' => key($item), 'typetext' => $item[key($item)]]); 
       } 
      } 
     } 
     $db = null; 
    } 
    catch(PDOException $e) { 
     echo $e->getMessage(); 
    } 
    exit(header("location: insert.php")); 
} 
?> 

我猜,因爲foreach包含$_POST['items'],而不是像$_FILES['items'],這是不行的。是這樣嗎?我擁有數組中的所有內容的主要原因是,我可以在數據庫中存儲這些項目的索引,以便在檢索單個帖子的內容時,我可以按正確順序放置它們。如果我以錯誤的方式去解決這個問題,有什麼更好的方法來做到這一點?

+0

另外,我的道歉我剛纔的問題的shoddiness,因爲我沒有提供足夠的信息和編輯它到地獄(儘管我從評論和答案中學到了很多東西)。我希望這個問題更清楚一點。 – rpivovar

+0

如果$ items數組中的某個數組是另一個數組,那麼您將不得不遍歷該數組。 – Difster

+1

你可以循環發佈文件和/或將它們粘合在一起,問題不清楚。 – rtfm

回答

1

您可以用$_FILES訪問文件輸入而不是內容可用的變量是name, type, tmp_name, error and size

foreach($_FILES['items'] as $index => $item){ 
    foreach ($item as $value) { 
    echo "$index : {$value['image']} <br>"; 
    } 
} 
相關問題