Mysql query for only current user

I’ve started using the wpdatatables plugin,
In the backend it has a place to enter a MySql query for it to create a table.

I have:

Read More
SELECT id, currentuserid, text, date_created
FROM  `1items` 
WHERE currentuserid = %d
ORDER BY  `1items`.`currentuserid` 

Which lists all the tables I need to pull from the database, however, I am wondering if there is a way to dynamically filter in MySql for only the current user’s ID.

In the second column “currentuserid” it pulls all the user’s ID’s and inputs them into the table.

Example: If I am logged in as user ID 4 – I would like the query to filter out the other users — as of now, The above query returns tables from all user ID’s.

When searching wordpress stackexchange, I located this: PHP MySQL query – return results for current user only
Which doesn’t work, or I am not using it right with wpdatatables.

Thanks!

Related posts

Leave a Reply

1 comment

  1. %d is a placeholder, it has no intrinsic value of its own. It’s used in a prepare statement to help protect against SQL injection attacks

    So you need to do something like this:

    $currentUser    = get_current_user_id();
    
    $wpdb->query( $wpdb->prepare( 
        "
            SELECT id, currentuserid, text, date_created
            FROM  `1items` 
            WHERE currentuserid = %d
        ", 
            $currentUser
    ) );
    

    As Brendan Long points out the order by doesn’t do anything when return a single user’s results.