我正在尝试根据mysql
表数据动态创建html表。
首先,通过将键与结果数组分开,将所有数据库列名称打印为html中的th
。现在结果数组如下所示
Array
(
[0] => Array
(
[0] => 25
[1] => http://google.com
)
[1] => Array
(
[0] => 26
[1] => http://hotmail.com
)
)
我想要这种方式的数组,因为我不知道每个数据库表有多少列。因此,我想在<td>
中动态打印它们。
foreach($result_array as $key => $val){
echo "<tr id=".$val[0].">";
echo "<td>".$val[1]."</td>";
echo "</tr>";
}
我想在$val[0]
的下一个步骤中增加一个。不像循环,它们在一个回合中为全部工作迈出了第一步,正如我在上面的foreach $val[0] $val[1]
中提到的那样,我希望0 and 1
在一个回合中动态地输入,而无需手工输入。
我想要这样
foreach($result_array as $key => $val){
echo "<tr id=".$val[$key].">"; // $key = 0
echo "<td>".$val[$key]."</td>"; // $key = 1
echo "</tr>";
}
答案 0 :(得分:1)
请尝试使用此代码。
<?php
$servername = "localhost";
$username = "YOUR USERNAME";
$password = "YOUR PASSWORD"; //if set password you mysql
$dbname = "YOURDATABASE";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
?>
<table>
<tr>
<th>Name</th>
</tr>
<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
//echo "<pre>";print_r($row[0]);
//echo "id: " . $row[0]. " - Name: " . $row[1]. " " . $row[2]. "<br>"; ?>
<tr>
<td><?php echo $row[1]; ?></td>
<?php } ?>