2011-08-22 76 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