Search code examples
phpwordpress

I got this error "Use of a direct database call is discouraged"


A few days ago, when I submitted a plugin to the WP repository, it showed the error "Use of a direct database call is discouraged WordPress.DB.DirectDatabaseQuery.DirectQuery" this error within several PHP files. I've tried various ways to fix the error but couldn't manage it. I follow WPCS, but the error still persists.Even i tried using the plugin (https://wordpress.org/plugins/plugin-check/) to detect errors in my local pc, but it didn't show any. Now, can I solve this error somehow?

                    `global $wpdb;
                    $table_name = $wpdb->prefix . 'orgsmtp_logs';

                    // Define the data to insert
                    $data_to_insert = array(
                        'recipient_email' => $email,
                        'sender_name' => $options['gmail_smtp_from_name'],
                        'subject'   => $subject,
                        'reply_email' => $replyemail,
                        'bcc_email' => $bccemail,
                        'cc_email' => $ccemail,
                        'message' => $message,
                        'status' => 'failed'
                    );
                    //Insert the data into the database table
                    $wpdb->insert($table_name, $data_to_insert);`

I follow the WPCS, but i did not receive any solution. So that I can fix the error and get approval from the WP repository.


Solution

  • The // db call ok looks like an old PHPCS style, not supported anymore.

    The correct "ok" comment is:

    $rows_affected = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            ...
    

    (covers both DirectQuery and NoCaching)