如何在Wordpress中插入数据?

时间:2013-10-17 12:30:03

标签: php database wordpress insert

我尝试将数据插入名为Ships的表中,但遗憾的是它不起作用。我粘贴了代码,以便更好地了解我如何编写脚本。非常感谢任何帮助!

<?php
require_once('../../../wp-config.php');
global $wpdb;

?>

<?php

    $json_data = $_POST['info'];

    if( isset($json_data) ){

        $eniNumber  = $json_data['EniNumber'];
        $name       = $json_data['Name'];
        $startDate  = $json_data['StartDate'];
        $rows       = $json_data['Rows'];

        $table_name = $wpdb->prefix . "Ships";
        $result = $wpdb->insert( $table_name, array(
            'eniNumber' => $eniNumber,
            'name' => $name,
            'startDate' => $startDate
        ) );

        if( $result ){
            echo json_encode("Entered data successfully");
        }else{
            echo json_encode("Insertion failed");
        }

    } else {
        echo json_encode( "What happened?" );
    }

?>

2 个答案:

答案 0 :(得分:6)

添加数据的实际方法是

<?php $wpdb->insert( $table, $data, $format ); ?>

$wpdb->insert( 
'table', 
array( 
    'column1' => 'value1', 
    'column2' => 123 
), 
array( 
    '%s', 
    '%d' 
) 
);

并使用

$wpdb->insert_id

获取插入ID

答案 1 :(得分:2)

您也可以参考这种插入方式

<?php
// if using a custom function, you need this
global $wpdb

$lastn = 'Last Name';
$firstn = 'First Name';
$wpdb->insert( 'clients', array( 'last_name' => $lastn, 'first_name' => $firstn ), array( '%s', '%d' ) )

?>