-2

i have input data for example : sex = male, i can query it like this:

$sex = $data['sex'];
            $query = $this->db->rawQuery("SELECT * FROM tbl_emp_information WHERE sex = $sex");
            echo json_encode($query);

but if i input sex = male and civil_status = single this query works:

 $sex = $data['sex'];
            $civil_status = $data['civil_status'];
            $query = $this->db->rawQuery("SELECT * FROM tbl_emp_information WHERE sex = $sex AND
            civil_status = $civil_status");
            echo json_encode($query);
            return;

this is the problem: how can i dynamically change the condition based on the inputby user

  • 1
    _"i can query it like this"_ - Actually, that query would throw a syntax error since you're missing the quotes around the value. However, you should _really_ use [prepared statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) with placeholders instead of injecting variables directly into the queries like that. – M. Eriksson Aug 25 '22 at 08:45
  • it won't throw an error because the value of male = 1 and female = 0, same with the civil status their value change when storing to database to int. – Michael Angelo Corral Aug 25 '22 at 08:48
  • Fair enough, but you should probably edit the question though since it now says: `sex = male`, which confuses things. – M. Eriksson Aug 25 '22 at 08:50
  • is it possible to solve this problem bro? please help:) – Michael Angelo Corral Aug 25 '22 at 08:54
  • Your question doesn't really make sense. What do you mean by "merge this into one query"? The only difference is that the second query has a couple of more conditions and a limit. Not sure what to "merge" here? Or are you asking how to dynamically add conditions to the query based on what inputs you get from the client/form? Please edit your question and explain in more detail what you want. – M. Eriksson Aug 25 '22 at 08:55
  • I think you got the right question. – Michael Angelo Corral Aug 25 '22 at 10:26

1 Answers1

-1

You can generate a query based on conditions that recieved from client. something like this:

$query = "SELECT * FROM tbl_emp_information";

$civil_status = $data['civil_status'];

if ($civil_status){
     $query .= " WHERE civil_status = '$civil_status'";
}

You can use query builders like laravel Eloquent for simplicity

Farid Saravi
  • 173
  • 1
  • 4