[英]Drupal 6 form iteration through data base query
我試圖在從數據庫查詢中提取的數組上運行foreach,但是由於某種原因它無法正常工作。 這是一個簡單的語法錯誤還是其他?
global $user
$ras = db_query("SELECT * FROM {table} WHERE id='%s'", $user->name);
$sas = db_fetch_array($ras);
$arr = array("one",2,3,"four",5);
$form['questionnaire'] = array (
'#type'=>'fieldset',
'#title'=> 'test', );
foreach ($arr as $id => $value){
$form['questionnaire']['fill'.$id] = array(
'#type'=>'textfield',
'#title'=> $value,
);
}
但是,以下將無法工作:
foreach ($sas as $id => $value){
$form['questionnaire']['fill'.$id] = array(
'#type'=>'textfield',
'#title'=> $value,
);
}
除非您的查詢返回單個結果,否則我會懷疑,因為您期望得到一個結果數組,否則語法將丟失某些內容。 db_fetch_array
將僅獲取一行。 所以你需要做這樣的事情。
$form['questionnaire'] = array(
'#type' => 'fieldset',
'#title' => 'test',
);
global $user;
$result = db_query("SELECT * FROM {table} WHERE id='%s'", $user->name);
// Remember that $row is an array where the key names map the column names in your table
// So if you have a column 'id' and another one 'value' you can access the
// value for one row like this $row['id] and $row['value']
while ($row = db_fetch_array($result)) {
$form['questionnaire']['fill' . $row['id']] = array(
'#type' => 'textfield',
'#title' => $row['column_name'],
);
}
更新07.02.2013 :使用foreach()
循環代替while()
foreach (db_fetch_array ($row) as $row) {
echo $row['name'];
}
語法看起來不錯,但顯而易見的答案是查詢沒有返回任何數據。 您有可能忘記了全局$ user嗎? 開發模塊可以幫助解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.