2

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

我将下面的代码与 SQL 语句的三种变体一起包含在内,以进行比较。我敢肯定,这对所有人来说都是显而易见的——除了我……

提前致谢!

D B


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

2 回答 2

1

改变这个

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

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

它会起作用

于 2012-05-01T06:03:02.597 回答
0

Satya 提供的解决方案是不够的。您应该正确地转义您的输入。

假设您$username包含一个"字符。这会破坏你的 SQL 语句。所以你应该使用准备好的语句,或者至少使用函数mysql_real_string_escape()

于 2012-05-01T20:42:09.803 回答