示例查询 1 -
SELECT ID,NAME FROM USERS
示例查询 2 -
SELECT Orders.OrderID as ID, Customers.CustomerName as Name, Orders.OrderDate as Date
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
如何将标题加载到 PHP 数组中? 我是说 查询 1 中的 ID,NAME 和查询 2 中的 ID,Name,Date
这就是我正在尝试做的事情:
我正在创建一个 PHP 函数,以根据任何给定的 MySQL-Select 查询自动创建 HTML 表
这就是我目前为止的情况
function createTable($query) {
$sql_link = Connect_MySQLi_DB();// Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
$headings = array('ID','Name','Date');//I need this array to create automatically
echo '<table>';
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<th>'.$headings[$x].'</th>';
}
echo '<tr>';
while ($row = $result->fetch_object()) {
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<td>' . $row->$headings[$x] . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
所以我需要自动创建 $heading 数组。 如果我能做到这一点,这个函数可以将任何 MySQL-Select 查询显示为 HTML 表
最佳答案
如果您使用 mysqli 那么 fetch_fields似乎可以完成这项工作。
编辑: 示例:
$res = $db->query('SELECT A.id,A.a,A.id + B.id AS idd FROM A natural join B');
var_dump($res->fetch_fields());
返回有关列 A.id、A.a 和有关 idd 列的信息(两个表都有其他列)。为了使其更短,我从输出中省略了一些字段。
array(3) {
[0]=>
object(stdClass)#3 (13) {
["name"]=>
string(2) "id"
["orgname"]=>
string(2) "id"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[1]=>
object(stdClass)#4 (13) {
["name"]=>
string(1) "a"
["orgname"]=>
string(1) "a"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[2]=>
object(stdClass)#5 (13) {
["name"]=>
string(3) "idd"
["orgname"]=>
string(0) ""
["table"]=>
string(0) ""
["orgtable"]=>
string(0) ""
// more fields here
}
}
关于php - 使用 PHP 将任何给定的 MySQL SELECT 查询显示为 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001719/