I need to secure a big SQL statement has a lot of conditions in its WHERE clause so I made an array for WHERE clause using $wpdb->prepare properly BUT an error happened while join this array together as a string in the final statement.
Here is some of my code .. Is that secure enough or it may cause an SQL injection?
P.S. I try to make another $wpdb->prepare in the last get_row function but the join function made quotes before and after WHERE clause so the statement generates an error.
foreach( $args as $field => $field_value ) {
if( ! is_null( $field_value ) ) {
switch( $field ) {
case 'id': {
if( is_numeric( $field_value ) && ( intval( $field_value ) > 0 ) ) {
$where[] = $wpdb->prepare( 'tbl_names.id = %d', $field_value );
}
} break;
case 'name': {
$where[] = $wpdb->prepare( 'tbl_names.name = %s', $field_value );
} break;
}
}
}
// NOT Working
return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$tbl_names} tbl_names WHERE %s", join( ' AND ', $where ) ), ARRAY_A );
// Working Good .. BUT Is it Safe??
return $wpdb->get_row( ( "SELECT * FROM {$tbl_names} tbl_names WHERE " . join( ' AND ', $where ) ), ARRAY_A );