0

I have a ajax query with multiple lines and I want the query to show only results that have an "active" status

$query .= "SELECT * FROM students ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'first_name LIKE "%'.$_POST["search"]["value"].'%" ';
 $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';

The second and third query is for when the user use the search box,

and I want the searchbox to also show only the "active" ones

I tried doing these to no avail

$query .= "SELECT * FROM students WHERE status='active' AND ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'first_name LIKE "%'.$_POST["search"]["value"].'%" ';
 $query .= 'OR status='active' AND last_name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= "SELECT * FROM students";
if(isset($_POST["search"]["value"]))
{
 $query .= 'first_name LIKE "%'.$_POST["search"]["value"].'% && status='active' ';
 $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'% && status='active' ';
bae
  • 125
  • 5
  • Does this answer your question? [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Alon Eitan Jun 23 '20 at 07:11
  • unfortunately, no. What I'm trying to do is show results through Ajax Query not insert data. – bae Jun 23 '20 at 07:12
  • You didn't ask about that, but using prepared statement will make your code secure and also solve this problem (And you need to escape the `'` using `\'`) – Alon Eitan Jun 23 '20 at 07:12
  • @AlonEitan ? How should I use a prepared statement? – bae Jun 23 '20 at 07:21
  • @bae Read [this tutorial](https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection) – Alon Eitan Jun 23 '20 at 07:28
  • 1
    @AlonEitan thank you I'll try learning prepared statements – bae Jun 23 '20 at 07:30

1 Answers1

-1

It is good to use prepared statements instead of it.below code just solve your problem but it is good to use prepared statements

Put AND in side if condition

 $query = "SELECT * FROM students WHERE status='active'";
    if(isset($_POST["search"]["value"])){
          $query .= 'AND ( first_name LIKE "%'.$_POST["search"]["value"].'%" 
                     OR last_name LIKE "%'.$_POST["search"]["value"].'%")';
    }
Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23