正如 Haider 所建议的,两种解决方案使用您的 $search_field_names 变量来调整您的查询:
$query=mysqli_query($mysqli, "SELECT ".implode(",", $search_field_names)." FROM table");
while($row=mysqli_fetch_assoc($query)) {
echo('<tr>');
for($i=0, $count=count($search_field_names);$i<$count;$i++) {
echo ('<td>'.$row[$i].'</td>');
}
echo('</tr>');
}
或者,因为你正在做一个 mysqli_fetch_assoc,这应该工作:
$query=mysqli_query($mysqli, "SELECT * FROM table");
while($row=mysqli_fetch_assoc($query)) {
echo('<tr>');
for($i=0, $count=count($search_field_names);$i<$count;$i++) {
// Using header name as the key to the column
echo ('<td>'.$row[ $search_field_names[$i] ].'</td>');
}
echo('</tr>');
}
编辑:到目前为止,我们只看到巧妙地循环 $search_field_names 以生成结果表。您在上一条评论中询问我们是否可以在构建查询约束时使用相同的技巧。一个问题是,您似乎想直接在查询中使用 $_POST。请不要这样做,这是SQL 注入的来源。另一个问题是,我们不可能永远聪明。如果所有字段都属于同一类型,我们可以这样做,但是如果您的搜索字段之一是日期或整数,那么编写和调试将变得非常困难。
所以,如果你真的需要聪明地处理你的查询,你可以这样做(假设所有搜索字段都是字符串值):
<?php
// Assuming you have a $post_array like so, where inputs have the same names as the column names in the database
// $post_array = array('username' => 'T', 'url' => 'http');
// Build constraints of the form column_name LIKE 'value%'
$constraints = array();
foreach ($post_array as $key => $value) {
$constraints[] = "$key LIKE ?";
$post_array[$key] = $value.'%';
}
// Build a query selecting the columns from $post_array, with corresponding constraints
// Note : replace " AND " by " OR " if you want the query to match ANY parameter.
$query_text = "SELECT ".implode(", ", array_keys($post_array))." FROM table WHERE ".implode(" AND ", $constraints);
// Prepare this query, we don't want SQL injections!
$query = $mysqli->prepare($query_text);
$bind = array();
foreach ($post_array as $key => $value) {
// We need to use our bind variables outside the scope of this loop, so we create them in $GLOBALS
$GLOBALS[$key] = $value;
// Array of references to our bind variables.
$bind[] = &$$key;
}
// Binding the parameters : we need as many 's' as there are inputs
$bindtypes = str_repeat('s', count($post_array))
call_user_func_array(array($query, 'bind_param'), array_merge( array($bindtypes), $bind ));
// Binding the retrieved columns
echo call_user_func_array(array($query, 'bind_result'), $bind);
$query->execute();
// Header row
echo '<tr>';
foreach ($post_array as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr>';
// Result rows
while ($query->fetch()) {
echo('<tr>');
foreach ($post_array as $key => $value) {
echo '<td>', $$key, '</td>';
}
echo('</tr>');
}
?>