0

I Write Code to Save data in the Wordpress database table (table name is wp_fafa)

But Can't Save data in

$qry = $wpdb->query( "INSERT INTO `wp_fafa` (titile,liveprice,changing,lowest,topest,time) VALUES ('" . trim($row->item(0)->nodeValue) . "','" . trim($row->item(2)->nodeValue) . "','" . trim($row->item(4)->nodeValue) . "','" . trim($row->item(6)->nodeValue) . "','" . trim($row->item(8)->nodeValue) . "','" . trim($row->item(10)->nodeValue) . "')");
$wpdb->query($qry); 
2
  • why do you use query method and not insert? Commented Feb 19, 2015 at 17:19
  • Because I want after save data .. update they with ON DUPLICATE KEY UPDATE ....... Commented Feb 19, 2015 at 17:27

2 Answers 2

1

The following code will properly store data in wp_fafa:

$wpdb->insert( $wpdb->prefix . 'fafa', 
    array( 
        'title'     => trim($row->item(0)->nodeValue),
        'liveprice' => trim($row->item(2)->nodeValue),
        'changing'  => trim($row->item(4)->nodeValue),
        'lowest'    => trim($row->item(6)->nodeValue),
        'topest'    => trim($row->item(8)->nodeValue),
        'time'      => trim($row->item(10)->nodeValue)   
    ), 
    array( 
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s'
    ) 
);
1

Make sure you have declared the $wpdb variable global $wpdb;. Also calling $wpdb->query() will execute the query for you, so no need to do it again.

I would also recommend using $wpdb->insert() as this escapes your data for you:

global $wpdb;
$wpdb->insert(
    $wpdb->prefix . 'fafa',
    array(
        'titile'    => trim( $row->item(0)->nodeValue ),
        'liveprice' => trim( $row->item(2)->nodeValue ),
        'changing'  => trim( $row->item(4)->nodeValue ),
        'lowest'    => trim( $row->item(6)->nodeValue ),
        'topest'    => trim( $row->item(8)->nodeValue ),
        'time'      => trim( $row->item(10)->nodeValue ),
    )
);
3
  • not working .. I use wpdb->prefix . 'fafa', /// array( // then work @mikemanager Commented Feb 19, 2015 at 17:31
  • Ah sorry, I missed out the $wpdb->prefix from my example. I have edited my answer. :) Commented Feb 19, 2015 at 17:49
  • 1
    ok. know how can i update all fields in your code with ON DUPLICATE KEY UPDATE ? @mikemanger Commented Feb 19, 2015 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.