2011-08-22 57 views
0

我想插入一些數據到數據表,wordpress插件。 數據是通過POST獲取的。 我有多個結果(採取後),但$ wpdb->插入只插入我最後的結果(實際上覆蓋數據)。這是爲什麼?Wordpress插入多行到數據表

這裏是我的代碼:

HTML:

echo '<label for="reduceri-post-category"><b>' . __("What categories should be the adverts", 'appplugin') . '</b></label><br /><br /><br />'; 
    ?> 

    <?php foreach ($the_data[categories] as $sat): ?> 
    <b> <?= $sat[name]; ?> <br /> </b> 
      <?php foreach ($sat[subcategories] as $cat): 
    ?> 

    &nbsp; &nbsp; &nbsp;<input type="checkbox" name="reduceri-post-category" value="<?= $cat[sid] ?>" /> <?php echo $cat[name]; echo $cat[sid]; ?><br /> 

    <? endforeach; ?> 
    <? endforeach; ?> 




global $wpdb; 


    $thedata['reduceri-post-category'] = $_POST['reduceri-post-category']; 


    $table_name = $wpdb->prefix . "reduceri"; 


    foreach ($thedata as $key => $value) { 
    if($post->post_type == 'revision') return; 
    if ($post->post_type == 'post'){ 

     $wpdb->insert($table_name, array('time' => current_time('mysql'), 'post' => $post->ID, 'category' => $value)); 
    } 
    } 

我該怎麼才能做的是​​能夠插入所有的結果,不僅是最後一個?非常感謝!

+0

從快速瀏覽代碼我會說它只能插入一次,而不是多次。而你的代碼可以從正確的縮進中受益。 – hakre

回答

0

什麼是reduceri-post-category

你說你在帖子中有多個值。這些多個值如何傳遞到您的插件? reduceri-post-category是否包含多個值?你對每個值使用不同的鍵嗎?例如,reduceri-post-category2/3/4

您正在使用foreach遍歷$thedata.但是我沒有看到代碼中的任何地方,您實際上在$thedata中創建了一個數組。所以你的foreach只會執行一次,它會根據裏面的內容執行$_POST['reduceri-post-category'];

我想你想要做的,很難說,這是兩種情況之一。

方案1 - 多交鍵保存數據你是

$thedata[foo1] = $_POST[foo1]; 
$thedata[foo2] = $_POST[foo2]; 
$thedata[foo3] = $_POST[foo3]; 
foreach ($thedata as $key => $value) { } 

或(pseudeocode)之後 - 單篇文章的關鍵握着你的所有類別的數據。所以你必須把它分開,然後在每一個上執行。

$thedata = explode("?", $_POST[reduceri-post-category]); 
foreach ($thedata as $key => $value) { }  
+0

我編輯了我的代碼,添加了reduceri-post-category的起源 – dana

+0

它看起來像是回顯了一大堆所有具有相同「名稱」的子類別的複選框。你必須給他們不同的名字 - 'name =「reduceri-post-category1」''name =「reduceri-post-category2」'。然後按照我向您提供的場景1中的說明進行操作。 – mrtsherman

+0

是的,但我永遠不知道有多少複選框實際上檢查..嗯...任何建議? – dana