1

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 );
GMB
  • 216,147
  • 25
  • 84
  • 135
Hady Shaltout
  • 606
  • 1
  • 9
  • 22

1 Answers1

0

Unfortunately, I think this will be the only answer for a while.

$count = 0;
$query = "SELECT * FROM {$tbl_names} tbl_names";

foreach( $args as $field => $field_value ) {
  if( ! is_null( $field_value ) ) {

    $count++;
    $query .= ( 1 == $count ) ? ' WHERE ' : ' AND ';

    switch( $field ) {
            case 'id': {
                $query .= $wpdb->prepare( 'tbl_names.id = %d', $field_value );
            } break;                    
            case 'name': {
                $query .= $wpdb->prepare( 'tbl_names.name = %s', $field_value );
            } break;                  
        }
    }
}

return $wpdb->get_row( $query, ARRAY_A );
Hady Shaltout
  • 606
  • 1
  • 9
  • 22