How can PHP code be optimized for performance and security when interacting with databases in WordPress plugins?

To optimize PHP code for performance and security when interacting with databases in WordPress plugins, it is important to use prepared statements to prevent SQL injection attacks and minimize database queries to reduce server load.

global $wpdb;
$table_name = $wpdb->prefix . 'my_table';

// Prepare a SQL query using prepared statements
$query = $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $id );

// Execute the query and fetch results
$results = $wpdb->get_results( $query );