我正在尝试创建一个函数,无论列数是多少,都可以更轻松地读取任何sql表。
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$i = 0;
$result = $db->query("SELECT * FROM $table_name");
while($data = $result->fetch_object()) {
$i++;
foreach($col_names as $col_name) {
$cols[] = $data->$col_name;
}
}
var_dump($cols);
$nr_cols = count($cols);
/*for($j = 0; $j <= $nr_cols $j++) {
$cols[$j] =
}*/
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$cp->read_table('newss', $col_names);
表格结构:
ID NewsTitle NewsDescrption
1 title description
10 sda sd
var_dump的当前输出是:
array (size=6)
0 => string '1' (length=1)
1 => string 'title' (length=5)
2 => string 'descroierererer' (length=15)
3 => string '10' (length=2)
4 => string 'sda' (length=3)
5 => string 'sd' (length=2)
当我以这种方式执行$cp->read_table('newss', $col_names);
时,预期的输出是回显表行:
<tr>
<td>1</td>
<td>title</td>
<td>description</td>
</tr>
<tr>
<td>10</td>
<td>sda</td>
<td>sd</td>
</tr>
根据David Jones的回答,UPDATE将第一块代码改为此。
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
foreach($results as $result) {
// how do I ouput dinamically here
//echo $result->$col_name...... this would lied to another array
}
}
答案 0 :(得分:1)
试试这个。您应该只选择传入的列而不是整个表来限制不需要的处理。
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
return $results;
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$results = $cp->read_table('newss', $col_names);
$table = '';
foreach ($results as $item) {
$table .= '<tr>
<td>'.$item->ID.'</td>
<td>'.$item->NewsTitle.'</td>
<td>'.$item->NesDescription.'</td>
</tr>';
}
var_dump($table);
这应该返回一个对象数组。然后,您可以访问循环中的每一列以显示您的表格。
更新:
你不应该循环并在方法中生成你的表,因为它被认为是通用的和可重用的。而是返回结果并在控制器或主PHP文件中循环。