2012-05-01 18 views
2

我試圖修改一個mySQL查詢(可以)返回更具體的結果。我已經爲該語句添加了一個變量,以便它查找jobID和UserName。將$ userName添加到語句會將其分解。mySQL在添加變量時出現中斷

我已經在下面的代碼中包含了用於比較的三種變體的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(""); 
    } 
} 

回答

1

改變這種

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

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

,也將努力

+1

好的,不,這太容易了。它必須更難 - 更復雜... :)感謝您的幫助! –

+0

如果是的話,接受答案 – Satya

+0

而且 - 是的,它確實有效 - 輝煌!謝謝Satya –

0

solution provided by Satya是不夠的。你應該正確地逃避你的輸入。

假設您的$username包含一個"字符。這會破壞你的SQL語句。所以你應該使用準備好的語句,或者至少使用函數mysql_real_string_escape()