Search code examples
mysqlinsertwordpressprepare

wpdb->insert into custom wp table using prepare()


Working on a time system in Wordpress and run into something strange problem with wp insert when inserting to a custom table.

I am running the following function in my functions.php

function clock_in() {

if ( isset( $_POST['punch-in'] ) && '1' == $_POST['punch-in'] ) {

    $user_id = get_current_user_id();

    global $wpdb;
    $wpdb->query( $wpdb->prepare(
                    "
                        INSERT INTO $wpdb->wp_diss_users_sessions
                        (session_id,session_begin)
                        VALUES ( %d, %s )
                    ", 
                        $user_id,'test' 

) );

I've tested the function with an update query to wp_users table to verify the function is firing appropriately as desired.

The error I am receiving is as follows:

WordPress database error: [You have an error in your SQL syntax;
check the manual that     corresponds to your MySQL server version 
for the right syntax to use near 
'(session_id,session_begin) VALUES ( 2, 'test' )' at line 2]
INSERT INTO (session_id,session_begin) VALUES ( 2, 'test' )

My Table is designed as such:

[session_id] - INT(11) PK NN
[session_begin] - VARCHAR(45)

I understand best practice is to use prepare so I am trying to build all of my queries appropriately. I do believe $wpdb->wp_diss_users_sessions = correct syntax to reference my custom table from researching. Maybe I'm overlooking something simple but my head hurts for tonight.

Thanks all


Solution

  • You get the error because you don't have a table name in your query:

    INSERT INTO (session_id,session_begin) VALUES ( 2, 'test' )
                ^ here should be a table name
    

    Just using $wpdb->wp_diss_users_sessions will not work, your table name will not appear magically inside the wpdb object. You have to store it there yourself.

    In this thread in the WordPress support forum it is suggested to add this in a function of your plugin/theme:

    $wpdb->myplugintable = $table_prefix . 'myplugintable';
    

    If you place this in a function, don't forget to pull $table_prefix inside its scope with the global keyword.

    Afterwards you can access the table name in the manner you intend.