插入到数据库中时出现Foreach问题

时间:2013-01-17 作者:Iulian Bozeanu

我不知道为什么这个foreach没有运行。当我发布文章时,只插入一次。应根据需要进行调整。你觉得有什么问题吗?

$array_produse = array();
for($i=1; $i<=8; $i++)
{
    $gramaj = isset($_POST[\'image\'.$i.\'_gramaj\']) ? $_POST[\'image\'.$i.\'_gramaj\'] : \'\';
    $pret = isset($_POST[\'image\'.$i.\'_pret\']) ? $_POST[\'image\'.$i.\'_pret\'] : \'\';

    $array_produse[$i][\'gramaj\'] = $gramaj;
    $array_produse[$i][\'pret\'] = $pret;
    $array_produse[$i][\'numar_produs\'] = $i;
}

foreach($array_produse as $produs)
{
   $wpdb->insert(
        \'produse\',
        array(
            \'id\' => $post_id,
            \'pret\' => $produs[\'pret\'],
            \'gramaj\' => $produs[\'gramaj\'],
            \'numar_produs\' => $produs[\'numar_produs\']
        ));
}

4 个回复
SO网友:shea

(See comments)

$wpdb->insert(
    \'produse\',
    array(
        \'id\' => $post_id,
        \'pret\' => $produs[\'pret\'],
        \'gramaj\' => $produs[\'gramaj\'],
        \'numar_produs\' => $produs[\'numar_produs\']
    ),
    array(
        \'%d\',
        \'%s\',
        \'%s\',
        \'%d\'
    )    
);
SO网友:Nabil Kadimi
// Turn on errors display
$wpdb->show_errors();

foreach($array_produse as $produs){

    // Prepare query
    $sql = $wpdb->prepare("
        INSERT INTO $wpdb->produse (\'id\', \'pret\', \'gramaj\', \'numar_produs\') 
        VALUES (%d, %s, %s, %s)", 
        $post_id, $produs[\'pret\'], $produs[\'gramaj\'], $produs[\'numar_produs\']
        )
    );

    // Execute query
    $wpdb->query($sql);

    // Show error if any
    $wpdb->print_error(); 

}
SO网友:Iulian Bozeanu

问题已解决。”来自db的id是主id,需要是索引。

SO网友:Iulian Bozeanu

最终代码,如果有人需要:

global $wpdb;

$array_produse = array();
for($i=1; $i<=8; $i++)
{
    $gramaj = isset($_POST[\'image\'.$i.\'_gramaj\']) ? $_POST[\'image\'.$i.\'_gramaj\'] : \'\';
    $pret = isset($_POST[\'image\'.$i.\'_pret\']) ? $_POST[\'image\'.$i.\'_pret\'] : \'\';

    if($gramaj != \'\' and $pret != \'\')
    {
        $array_produse[$i][\'id\'] = $post->ID;
        $array_produse[$i][\'gramaj\'] = $gramaj;
        $array_produse[$i][\'pret\'] = $pret;
        $array_produse[$i][\'numar_produs\'] = $i;
    }
}

foreach($array_produse as $produs)
{

    $wpdb->insert(
        \'produse\',
        array(
            \'id\' => $produs[\'id\'],
            \'pret\' => $produs[\'pret\'],
            \'gramaj\' => $produs[\'gramaj\'],
            \'numar_produs\' => $produs[\'numar_produs\']
        ),
        array(
            \'%d\',
            \'%s\',
            \'%s\',
            \'%d\'
        )
    );
}

结束