2010-10-22 82 views
0

查詢我有一個使用SQL查詢控制器動作:CakePHP的:添加變量在控制器

$tag = $this->params['tag']; 

    $this->set('projects', $this->Project->query('SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE $tag')); 

正如你可以在看到底我想用一個where子句與$標籤可變的,但我我不確定句法會怎麼樣。由於我得到的錯誤

Unknown column '$tag' in 'where clause' 

有人可以引導我在正確的方向嗎?

鉭,

Jonesy

回答

-3

修改您的查詢爲:

$this->set('projects', 
$this->Project->query("SELECT * FROM projects 
         INNER JOIN projects_tags 
         ON projects.id = projects_tags.project_id 
         INNER JOIN tags ON projects_tags.tag_id = tags.id 
         WHERE tags.tag LIKE '" . $tag . "'") //problem was here 
        ); 

,它會工作。

+4

聖SQL注入等待發生,蝙蝠俠! – deceze 2010-10-22 09:37:40

+0

目前,逃避SQL注入是不成問題的。 – fabrik 2010-10-22 09:38:49

+0

你至少應該注意到,OP似乎並不太在意。按原樣使用代碼會很糟糕。 – deceze 2010-10-22 09:43:02

1

php中有一個difference between single and double quotes ...基本上,單引號不評估變量...用雙引號代替 ,我認爲,像也將需要使用單引號..我真的不知道

"SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE '$tag'" 

我知道..我知道..人們會開始說話有關SQL注入..和需要的景觀...... caracters這是另一個問題=)

好運!

4

我強烈建議您使用Cake ORM而不是原始查詢,特別是如果您要將URL參數插入到其中。 HABTM表中的條件可能會非常棘手,但您也可以使用Cake的ORM語法來構建連接!

閱讀說明書,第3.7.6.9 Joining tables

+0

你說得好。我打算留出一些時間來學習Cake ORM。主要優點是什麼?爲什麼它們比原始的sql查詢好得多? – iamjonesy 2010-10-22 14:18:59

+2

主要優點是內置的防禦SQL注入,與數據源的鬆散耦合,更好的可移植性,通常改進的可讀性和可維護性,支持模型回調和查詢緩存。這只是爲了讀取操作。 Cake的ORM並不是世界上最偉大的,但它確實比原始SQL有顯着的改進。 – 2010-10-22 15:14:16

3

如果您想使用Cake的ORM,下面的代碼應該提供的結果相當於你的原始SQL查詢:

$this->loadModel('ProjectsTag'); // Load the joining table as pseudo-model 

// Define temporary belongsTo relationships between the pseudo-model and the two real models 
$this->ProjectsTag->bindModel(array(
    'belongsTo' => array('Project','Tag') 
)); 

// Retrieve all the join-table records with matching Tag.tag values 
$result_set = $this->ProjectsTag->find('all',array(
    'conditions' => array('Tag.tag LIKE' => "%{$tag}%") 
)); 

// Extract the associated Project records from the result-set 
$projects = Set::extract('/Project', $result_set); 

// Make the set of Project records available to the view 
$this->set(compact('projects'));