I will be tempted to create a dispatch table that calls a function for each query parameter. This allows you to create a whitelist of secure query parameters. I would also use parameterized statements to help protect against SQL injection (that your existing code is not protected from). PDO simplifies the use of parameterized statements.
Creating a separate function for each request parameter may seem unnecessary at first, but this means that you can put all your conditions in a separate file, thereby preserving the main function of the request. It also facilitates the implementation of future improvements.
The following is an example of a non-standard example. It should not be ready to cut and paste into the application. This is just to give you an idea of ββwhat I mean. In a real application, among other things, you need to enable error checking and, most likely, move the material to connect to the database to another location.
// ** query_params.php ** function query_brand () { return "brand = ?"; } function query_price () { return "price BETWEEN ? AND ?"; } function query_category () { return "category = ?"; } // ** product_search.php ** function search () { // Build a test GET array. $_GET = array( 'brand' => 'HTC', 'price' => array(100, 200), 'category' => 'Android Mobiles' ); // Build a dispatch table of safe query parameters. $dispatch = array( 'brand' => 'query_brand', 'price' => 'query_price', 'category' => 'query_category' ); // An array to hold the conditions. $cond = array(); // An array to hold the bind values. $bind = array(); foreach ( $_GET as $param => $value ) { if( isset($dispatch[$param]) ) { $cond[] = call_user_func( $dispatch[$param] ); $bind[] = $value; } } $sql = "SELECT item, brand, price, category " . "FROM products"; if( count($cond) ) { // Combine the conditions into a string. $where = implode( ' OR ', $cond ); $sql .= " WHERE $where"; } // Use PDO to connect to the database. This should // probably be done somewhere else. $dbh = new PDO( "mysql:host=localhost;dbname=$dbname", $user, $pass, ); // Prepare the SQL statement. $stmt = $dbh->prepare( $sql ); // Execute the statement, passing the values to be // bound to the parameter placeholders. $stmt->execute( $bind ); // Fetch and return results... }
source share