Search code examples
phpmysqlxamppbackendsql-like

I am trying to run a query in php its working in phpMyAdmin but not in script


Iam trying to fetch related articles for a blog based project Query :

 $query = mysqli_query($con, "SELECT * FROM posts WHERE cat_id like '%$cat_arr[i]%' AND NOT post_id = '$postid'");

Problem : When ran in phpMyAdmin as a normal query it is fetching 3-4 rows as required but in scripts, it is fetching all rows in the posts table


Solution

  • It seems that the variable '%$cat_arr[i]% is blank.

    So if you are running the query:

    $query = mysqli_query($con, "SELECT * FROM posts WHERE cat_id like '%$cat_arr[i]%' AND NOT post_id = '$postid'");
    

    Instead of two conditions, only one condition post_id = '$postid' is getting into consideration.

    If we pass blank in LIKE %%, it is equal to not adding the conditon.

    So, best solution is to evaluate the variable first:

    if (isset($cat_arr[i]) && ! empty($cat_arr[i]) && ! empty($postid)) {
     $query = mysqli_query($con, "SELECT * FROM posts WHERE cat_id like '%$cat_arr[i]%' AND NOT post_id = '$postid'");
    }
    else {
     // Another condition
    }