0

I have a custom database in my WordPress site where I want to save multiple values to one row.

Let's say I have an entry:

  • id: auto increment
  • pageid: id of current page
  • time: text (is an array created with implode)

Example:

id  pageid  time
1   1       121212,121314,121415
2   2       121212,121314

What I am trying to achieve is a way I can extend the "time" field. Every time the function goes off, I want a timestamp added to the existing values.

So it would look like this:

id  pageid  time
1   1       121212,121314,121415, 181920
2   2       121212,121314, 292929, 988339

What would be the best way to solve this and how?

function custom_setup_db(){
    global $wpdb;
    $table_name = "customdb"; 
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
      id mediumint(9) NOT NULL AUTO_INCREMENT,
      userid mediumint(9) NOT NULL,
      timestamparray text,
      UNIQUE KEY id (id)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );    
}

function wp_install_data(){
    global $wpdb;

    $table_name = 'customdb';
    $timestamparray = array();
    array_push($timestamparray, '121212', '131415', '121316');
    $timeofvisit = implode(",", $timeofvisit);

    $wpdb->insert( 
        $table_name, 
        array( 
            'timeofvisit' => $timeofvisit,
            'userid' => '2'
        ) 
    );   
}
  • 1
    I believe the wpdb class should be your friend. codex.wordpress.org/Class_Reference/wpdb. Pulling the row $wpdb->get_row('query', output_type, row_offset); and modify the array seems the way to go. – jdm2112 Apr 22 '15 at 19:07
  • 1
    As written, there is really nothing specifically WordPress about the question. There are at least a handful of ways to stored data similar to what you are asking but they are all pretty much pure PHP/MySQL. Perhaps you could provide more context to the question or, even better, code? – s_ha_dum Apr 22 '15 at 19:23
  • I added some code above, but i really do not know how to achieve what i am trying to. – user71025 Apr 22 '15 at 19:58
  • why push the values into an array? seems to make more sense to store each visit as a row, especially if you intend to do any meaningful querying on it. – Milo Apr 22 '15 at 20:26
  • Yeah i was thinking this to, but as this is supposed to be a multisite installation i was afraid that it would get out of hand due to the amount of visits – user71025 Apr 22 '15 at 22:34
0

Your table does not have a timeofvisit column. The second value of $wpdb->insert expects column value pairs, see here. Try

$wpdb->insert( 
    $table_name, 
    array( 
        'timestamparray' => $timeofvisit,
        'userid' => '2'
    ) 
);

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.