2013-01-21 91 views
0

如果我有一個名爲書表什麼是在Drupal選擇查詢的正確語法

Column 1 = current_user 
, Column 2 = page_length 
, Column 3 = author 
, Column 4 = title 

我想選擇對應於當前登錄的3列2和4的數據用戶。以下正確的語法?

<? 
global $user; 
$user_id=$user->name; 
db_query('SELECT * FROM {book} WHERE current_user=$user_id', $page_length, $author, $title); ?> 
+0

首先,您必須QUOT查詢。但是你想選擇什麼? –

回答

1

一些提示:

  1. 你需要確保的是使用SQL語句中的引號字符串。
  2. 由於用戶名是用戶提供的字符串,因此應該使用參數轉義來防止SQL注入。
  3. 您並不需要將用戶名分配給單獨的變量($user_id)以使用它。
  4. 您需要從返回值db_query中檢索結果。

固定碼:

<?php 
global $user; 
$res = db_query("SELECT page_length, author, title FROM {book} WHERE current_user = '%s'", $user->name); 
$row = db_fetch_array($res); 
// now $row['page_length'], $row['author'] and $row['title'] are filled in with values if the query was successful 
?> 
+0

因此,當我嘗試這樣做時,查詢認爲我有一列標記爲用戶名(例如,student2,但它只是一個名爲'user_id'的列內的值,所以我得到錯誤「user warning:Unknown column' ...' – ingrid

+0

此外,它爲什麼... current_user =%s「,$ user-> name);?目前還不清楚current_user和$ user-> name的連接方式 – ingrid

+0

我還知道student2存在於current_user列 – ingrid