使用foreach在wordpress数据库上插入数据

时间:2014-10-28 16:56:33

标签: mysql wordpress sql-insert

在Wordpress上,我想在我创建的用于目的的表上插入数据,我使用全局$ wpdb和insert。 我有更多要插入的数据,是否可以在我的数组中插入foreach或任何循环?

提前谢谢你, 让查尔斯

global $wpdb;
        $name="JC";
        $email="jcdarocha@gmail.com";
        $website="www.jcdarocha.co.uk";
        $country="UK";
        $message="hello World";

        global $wpdb;
        $wpdb->insert( 'my_table',
         array( 
                '$name' => '$name', 
                '$email' => $email,
                '$website' => $website,
                '$country' => $country,
                '$message' => $message
            ), 
        array( '%s', '%d' ) );

2 个答案:

答案 0 :(得分:0)

使用$ wpdb->查询并将所有数据连接成字符串

$insert = "INSERT INTO my_table (name, email, website, country, message) VALUES ";
foreach( $datas as $data ) {
  $insert .= sprintf("('%s','%s','%s','%s','%s'),", $data['name'], $data['email'], $data['website'] , $data['country'], $data['message'] )

}

$wpdb->query( rtrim($insert, ','));

答案 1 :(得分:0)

    global $wpdb;
    $name="JC";
    $email="jcdarocha@gmail.com";
    $website="www.jcdarocha.co.uk";
    $country="UK";
    $message="hello World";

    global $wpdb;
    $wpdb->insert( 'my_table',
    array( 
            'name' => $name, 
            'email' => $email,
            'website' => $website,
            'country' => $country,
            'message' => $message
        ) );