1

I would like to create dinamically in my php class a where clause from a array where are defined search fields.

$search = array('brand' => 'something', 'model' => 'something');
$myclass->testarr($search);

CLASS

public function testarr($search){

    if (!empty($search)){

        foreach ($search as $key => $value) {

            $where = $key . " = " . $value;
        }

    $clause = !empty($where) ? 'WHERE' : '';

    $result = $this->db->mysqli->query
    ("SELECT * FROM tb1 $clause $where");

    }

}

My problem is to manage a clause with more than one field by entering the suffix AND. How could I do that? Thanks

1
  • 2
    mysqli_stmt_bind_param is a better option Commented Dec 6, 2013 at 11:10

2 Answers 2

5

I would advice to do this:

$where = array();
if (!empty($search) && is_array($search)) {
    foreach ($search as $key => $value) {
        $where[] = $key . " = " . $value;
    }
}
if (!empty($where))
    $query = sprintf('SELECT * FROM tb1 WHERE %s', implode('AND ', $where));
else
    $query = 'SELECT * FROM tb1';

Using implode makes things easier.

Beware however of escaping issues, as your code is prone to security issues.

Sign up to request clarification or add additional context in comments.

2 Comments

Clean, but $where may be empty, and "WHERE" should be removed
No one should use this insecure/unstable answer. A properly implemented prepared statement is called for.
1

There is one flaw with your code: $where = $key . " = " . $value; will overwrite $where in each iteration, you need to use .= to concatenate. Then this could be done e.g. the following way

$where = "";
foreach ($search as $key=>$value) {
    if (!empty($where)) $where .= " AND ";
    $where .= $key . " = " . $value;
}
$clause = !empty($where) ? 'WHERE '.$where : '';

This will add a AND before every condition, starting from the second (because for the first the if will fail).

I suggest researching prepared statements, these will make your code alot more secure and once you understood the concept, they become quite easy to handle (imo). Because if that is most of your code at the moment, you are quite vulnerable to SQL injections.

3 Comments

I thank you for your solution. Can you tell me how to do it with prepared statements? Thanks
Well okay, this code wouldn't be much simpler, as you'd have to iterate twice over $search (once for keys and once for values) - I think Michaël Perrin is quite elegant
No one should use the insecure/unstable snippet. A properly implemented prepared statement is called for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.