[英]Drupal 6 form iteration through data base query
I'm trying to run a foreach over an array pulled from a db query but for some reason it isn't working. 我试图在从数据库查询中提取的数组上运行foreach,但是由于某种原因它无法正常工作。 Is this a simple syntax error or something else?
这是一个简单的语法错误还是其他?
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,
);
}
However, the following wont work: 但是,以下将无法工作:
foreach ($sas as $id => $value){
$form['questionnaire']['fill'.$id] = array(
'#type'=>'textfield',
'#title'=> $value,
);
}
Unless your query returns a single result, which I doubt since you're expecting an array of results, your syntax is missing something. 除非您的查询返回单个结果,否则我会怀疑,因为您期望得到一个结果数组,否则语法将丢失某些内容。
db_fetch_array
will only fetch one row. db_fetch_array
将仅获取一行。 So you need to do something like this. 所以你需要做这样的事情。
$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'],
);
}
Update 07.02.2013 : Using a foreach()
loop instead of while()
更新07.02.2013 :使用
foreach()
循环代替while()
foreach (db_fetch_array ($row) as $row) {
echo $row['name'];
}
The syntax looks right but the obvious answer is that the query isn't returning any data. 语法看起来不错,但显而易见的答案是查询没有返回任何数据。 Is it possible thst you've forgotten global $user?
您有可能忘记了全局$ user吗? Devel module can help with this.
开发模块可以帮助解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.