phpmysql

mySQL breaks when adding a var


I'm attempting to modify a mySQL query (that works) to return a more specific result. I've added a variable to the statement so that it looks for jobID AND UserName. Adding the $userName to the statement breaks it.

I've included the code below with the three variations of the SQL statement for comparison. I'm sure it's something obvious - to everyone but me...

Thanks in advance!

DB


// get all applicants from a User
public function GetAllMyApplications($from=false, $to=false, $user_name)
    {
    global $db;
    $applicants = array();

    if ($from >= 0 && $to > 0)
            {
                $sql_limit = ' LIMIT ' . $from .', ' . $to;
            }
            else
            {
                    $sql_limit = '';                
            }

    $user_name = "Bob Bobberton"; // reset this var for testing

    $sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' ORDER BY name ASC ' . $sql_limit; // This was the original SQL that worked

    $sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = ' . $user_name . ' ORDER BY name ASC ' . $sql_limit; // Added "and" $user_name - it breaks 

    $sql = 'SELECT * FROM '.DB_PREFIX.'job_applications WHERE job_id = '. $this->mJobId . ' AND name = "Bob Bobberton" ORDER BY name ASC ' . $sql_limit; // Replace var with value "Bob Bobberton" and it works


    $result = $db->query($sql);
    while ($row = $result->fetch_assoc())
    {
            $applicants[] = array('id' => $row['id'], 
                    'job_id' => $row['job_id'], 
                    'name' => $row['name'], 
                    'email_address' => $row['email_address'], 
                    'message' => str_replace(array("\r\n", "\r", "\n"), "<br />", $row['message']),
                    'resume_path' => base64_encode($row['resume_path']),
                    'created_on' => $row['created_on'],
                    'ip' => $row['ip']);
    }

    if (isset($applicants))
    {
        return $applicants;
    }else{
        return("");
    }
}

Solution

  • change this

    ' AND name = ' . $user_name . ' ORDER BY name ASC '
    

    to

    " AND name = '" . $user_name . "' ORDER BY name ASC "
    

    and it will work