3

I tried to insert data to a table named Ships, but sadly it doesn't work. I pasted the code, to give you a better view about how I wrote my script. Any help is much appreciated!

<?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?" );
    }

?>
Tolga Demir
  • 161
  • 2
  • 11
  • Is it wordpress data structure ? – Vinod VT Oct 17 '13 at 12:32
  • You should use custom post types (http://codex.wordpress.org/Post_Types) instead of creating you own db tables. It'll save you hours of work and spare you having to deal with a database directly. – Joren Oct 17 '13 at 12:32
  • I have to save over 3M records, so I think that a database would be much better to save and get those data. I want to save the data in the database, so please say anything related for what I ask for. – Tolga Demir Oct 17 '13 at 12:39

2 Answers2

6

actual way to add data is

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

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

and use

$wpdb->insert_id

to get insert id

Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
  • Thanks buddy! There is another problem. :( After I insert another data, the insertion process fails. Ans also, the first time when I insert data, I get to see that the id starts with 0 instead of 1 in the table named Ships. What can I do? – Tolga Demir Oct 17 '13 at 13:45
  • you can set the auto increment start from 1 instead of 0 ALTER TABLE Ships AUTO_INCREMENT = 1 – Ram Sharma Oct 17 '13 at 13:52
  • Yeah, strangely, the auto increment option wasn't on, so I had to enable it. Thanks mate! – Tolga Demir Oct 17 '13 at 13:54
2

You can also refer this way of inserting

<?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' ) )

?>
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
harry gates
  • 423
  • 3
  • 2