添加var时mySQL会中断

时间:2012-05-01 05:58:16

标签: mysql

我正在尝试修改mySQL查询(有效)以返回更具体的结果。我在语句中添加了一个变量,以便它查找jobID和UserName。将$ userName添加到语句会破坏它。

我已将下面的代码包含在SQL语句的三个变体中以供比较。我确信这对我来说很明显 - 除了我......

提前致谢!

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("");
    }
}

2 个答案:

答案 0 :(得分:1)

更改此

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

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

它会起作用

答案 1 :(得分:0)

solution provided by Satya还不够。你应该正确地逃避你的输入。

假设您的$username包含"个字符。那会打破你的SQL语句。因此,您应该使用预准备语句,或者至少使用函数mysql_real_string_escape()