2013-03-02 2 views
6

Cakephp에서 MySQL 쿼리를 직접 만들려고합니다.CakePHP에서 커스텀 MySQL 쿼리를 만드는 법?

이것은 내 LocationsController.php :

<?php 
App::uses('Location', 'Model'); 
class LocationsController extends AppController 
{ 
    public $helpers = array('Html', 'Form'); 
    function index() 
    { 
     $this->loadModel("Location"); 
     $this->Location->get(); 
    } 
} 

이것은 내 LocationModel.php :

<?php 
App::uses('AppModel', 'Model'); 
class LocationModel extends Model { 

    public $name = 'Location'; 

    public function get() 
    { 
     $this->Location->query("SELECT * FROM locations;"); 
    } 
} 

당신이 볼 수 있듯이, 난 그냥 간단한 쿼리를 수행하려고하지만 그것은 작동하지 않습니다. 이 오류를 얻을 :

Error: 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 'get' at line 1 

내가 발견 같은 마법의 방법 중 하나를 사용하십시오 ("모든") 대신, 작동 ...

당신은 문제가 무엇인지 볼 수 있을까요? 나는 정말로 할 수 없다. 그리고 나는 단지 간단한 작업을하려고 노력하고있다!

+1

당신이 만약 모델 내에서, 당신은 $this->Location->query();을 사용하지 않아야합니다,

또한 오류를 일으키는 SQL 문으로 get을 실행하지만 것 'Location' 모델에서'$ this-> query ('SELECT * FROM locations')가 아닌가? ' – AlienWebguy

+0

아래 답변을 확인하고 다음에 어떤 일이 발생하는지 알려주십시오! – Karma

+1

당신이 이미 위치 모델을 가지고 있고'find (all)'을 할 수있을 때 여기에 커스텀 쿼리를 사용하는 건 정당한 이유가 없다. ... 정말로 커스텀 쿼리를 사용해야하는지 항상 스스로에게 물어야한다. 그러면 당신은 당신이 정말로 필요로하지 않는다는 것을 알게 될 것입니다. – mark

답변

7

위치 모델의 클래스 이름 Location하지 LocationModel해야한다.

이 때문에 CakePHP는 Locations 데이터베이스 테이블에 'generic'모델을 생성하고 사용자 모델 대신 해당 모델을 사용합니다. 이 일반 모델이 하지get() 방법을 가지고 있기 때문에 '단순히 $this->query();

+1

SQL 인젝션을 막기 위해'query()'가 실행됩니까? –

+6

@FranciscoCorrales ** 아니요 ** 이스케이프되지 않은 변수가 포함 된 리터럴 쿼리를 전달하면 준비된 문을 지원합니다 (소스 [here] (https://github.com/cakephp/cakephp/blob) 참조). /2.4.9/lib/Cake/Model/Model.php#L3297)). 다음과 같이 사용하십시오 : $ this-> query ('SELECT * FROM foo where id =? 또는 somefield =?', array (123, 'foo')); – thaJeztah

3

위치 컨트롤러가 있어야한다 :

<?php 
App::uses('Location', 'Model'); // Y do u need this? 
class LocationsController extends AppController 
{ 
    public $helpers = array('Html', 'Form'); 
    function index() 
    { 
     $this->loadModel("Location"); 
     $this->LocationModel->getLocations(); // I will strongly discourage using get() 
    } 
} 

위치 모델이 있어야한다 :

<?php 
App::uses('AppModel', 'Model'); 
class LocationModel extends Model { 

    public $name = 'Location'; 

    public function getLocations() // Try to avoid naming a function as get() 
    { 
    /** Choose either of 2 lines below **/ 

     return $this->query("SELECT * FROM locations;"); // if table name is `locations` 
     return $this->query("SELECT * FROM Location;"); // if table name is `Location` since your public name is `Location` 
    } 
} 
+0

'query()'가 SQL 삽입을 방지합니까? –

+0

아니요. 그렇지 않습니다. 그러나'is_int()'나'ctype_alnum'과 같은 PHP 함수를 사용하여 변수를 검사 할 수 있습니다. – Karma

+0

글쎄, 이걸보고 저의 생각을 알려주세요. https://github.com/cakephp/ cakephp/blob/2.4.9/lib/Cake/Model/Model.php # L3297 –

관련 문제