2011-12-12 4 views
0

내 코드 그래서 나는 오류를 가지고 지금까지SQL 구문에 오류가 있습니다.

 $limitText =""; 
     if($history_length){ 
      $limitText = ' limit '. $history_length; 
     } 

     if(!$history_days){ 
      $history_days = '180'; 
     } 
$db = $this->getInvokeArg('bootstrap')->getPluginResource('db')->getDbAdapter(); 
     //changing code to add min(currBalance) -- as sum(points) is valid only for debit. Also sort by desc instead of (major bug) 
     $history_stmt = $db->query("SELECT sum(points) as points,credit_date,min(currBalance) as currBalance,extRefId,transactedAt,pointType FROM credits where userid = '".$userid."' and credit_date >= date('now','-".$history_days." days') group by extRefID,pointType order by creditid desc ".$limitText); 
     $history_results = $history_stmt->fetchall(); 

     $expiry_stmt = $db->query("SELECT availablePoints,expiry_date FROM credits where userid = '".$userid."'and availablePoints > 0 and expiry_date <= date('now','+".$expiry_duration." days') order by expiry_date asc "); 
     $expiry_results = $expiry_stmt->fetchall(); 

입니다

<b>Message:</b> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''-180 days') group by extRefID,pointType order by creditid desc' at line 1 </p> 

나는

+0

정확히 무엇을하고 싶습니까 ?? 'DATEDIFF' 또는'DATE_ADD' 사용 – diEcho

답변

5

당신이 잘못에 MySQL Date function를 사용하는 것 같습니다 솔루션을 미세 할 수없는 나는 무엇을 할 수 있는지 사실, 대신 실제로 php date 함수를 사용하려고 계획 했습니까? 예를 들어.

"[...] credit_date >= '".date('-'.$history_days.' days')."' group by [...]" 

만 변수 (예 : $ history_days) 큰 따옴표 (")로 둘러싸인 문자열 PHP에 의해 확장 얻을 것이다,하지만 기능은 경우 호출

"[...] credit_date >= date('now','-".$history_days." days') group by [...]" 

당신은 작성해야 할 것이다. 당신은 함수 호출을 문자열 안에 감싸고 php는 그것을 인식 할 수 없으며, php에 의해 먼저 실행되는 대신 mysql을 전달할 것이다. 그러나 php가 그것을 평가하기를 원하기 때문에 그것을 제외시켜야한다. 문자열 상수에서 연결 연산자 (.)를 문자열에 추가하십시오.

그러나 php date 함수 호출도 올바르지 않은 것 같습니다. 보안에

"[...] credit_date >= DATE_SUB(NOW(), INTERVAL '$history_days' DAY) group by [...]" 

그리고 한 일반 노트 :이 같은 "현재 날짜 마이너스 일의 일정 금액"최고의 사용 MySQL의 날짜 함수를 얻을 그것은 당신이 제공하는 스크립트의 부분에서 분명하지 않다, $history_days, $history_length, $user_id 또는 $expiry_duration (SQL 문 내에서 사용되는 변수)의 값이 사용자가 설정하는 가장 먼 기회 일 경우 SQL 문에 직접 삽입하면 안되지만 do something to prevent SQL injection입니다.

+0

:) 감사합니다 멋진 답변 – John

관련 문제