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?
    – Milo
    Feb 19, 2015 at 17:19
  • Because I want after save data .. update they with ON DUPLICATE KEY UPDATE .......
    – Mortzea
    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
    – Mortzea
    Feb 19, 2015 at 17:31
  • Ah sorry, I missed out the $wpdb->prefix from my example. I have edited my answer. :)
    – mikemanger
    Feb 19, 2015 at 17:49
  • 1
    ok. know how can i update all fields in your code with ON DUPLICATE KEY UPDATE ? @mikemanger
    – Mortzea
    Feb 19, 2015 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.