Is there a way to condense this code?

I am just wondering if there is a better way to write this snippet of code. (Ignore the “+” signs, I am copying it from a GitHub diff)

  • $query = "SELECT c.course_id, c.cat_id, cc.cat_name, c.created_date, ".
  •    "c.title, c.description, c.notify, c.copyright, c.icon, c.release_date, c.primary_language, ".
    
  •    "c.end_date, c.banner FROM %scourses c ".
    
  •    "INNER JOIN %scourse_cats cc ON c.cat_id = cc.cat_id";
    
  • if ($member_id != -1) {
  •    $query = $query." INNER JOIN %scourse_enrollment ce ON c.course_id = ce.course_id".
    
  •    " WHERE ce.member_id = ".$member_id;
    
  • }
  • if ($course_id != -1) {
  •    $query = $member_id == -1 ? $query . " WHERE " : $query . " AND ";
    
  •    $query = $query."c.course_id = ".$course_id;
    
  • }
  • if ($clause) {
  •    $query = ($member_id == -1 && $course_id == -1) ? $query." WHERE " : $query." AND ";
    
  •    $query = $query.$clause;
    
  • }

Hello sdaityari,

you may condense SELECT:

$query = "SELECT c.course_id, c.cat_id, cc.cat_name, c.created_date, ".
        "c.title, c.description, c.notify, c.copyright, c.icon, c.release_date, c.primary_language, ".
        "c.end_date, c.banner FROM %scourses c ".
        "INNER JOIN %scourse_cats cc ON c.cat_id = cc.cat_id";

might be simplified to this:

$query = "SELECT c.*, cc.cat_name".
        " FROM %scourses c ".
        "INNER JOIN %scourse_cats cc ON c.cat_id = cc.cat_id";

and parts like this:

$query = $query." INNER JOIN %scourse_enrollment ce ON c.course_id = ce.course_id".
" WHERE ce.member_id = ".$member_id;

writing like this:

$query .= " INNER JOIN %scourse_enrollment ce ON c.course_id = ce.course_id".
" WHERE ce.member_id = ".$member_id;

Also, in ternary operators, like here:

 $query = ($member_id == -1 && $course_id == -1) ? $query." WHERE " : $query." AND ";

It’s not necessary to use parenthesis, so you can get rid of them.

This one:

$query = $member_id == -1 ? $query . " WHERE " : $query . " AND ";

would became:

$query .= $member_id == -1 ? " WHERE " : " AND ";

Good luck!

A better way to write that code would be ti use PREPARE and BIND instead of QUERY.