简体   繁体   English

在php中包含sql数据的HTML表格(表格行取决于sql列)

[英]HTML table with sql data in php (table row depend by sql columns)

Hello i got this sample data in sql 您好,我在sql中获得了此示例数据

$data = array(
  array('id' => '1','name' => 'name1','surname' => 'surname1'),
  array('id' => '2','name' => 'name2','surname' => 'surname2'),
  array('id' => '3','name' => 'name3','surname' => 'surname3'),
  array('id' => '4','name' => 'name4','surname' => 'surname4')
);

I want to dispplay in in html table but my code didnt work : 我想在html表中显示,但我的代码无法正常工作:

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html">
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
            <thead>
                <tr>
                    <th align="left" valign="middle">id</th>
                    <th align="center" valign="middle">name</th>
                    <th align="center" valign="middle">surname</th>                    
                </tr>
            </thead>
            <?php
            $result = mysql_query($select_data);
            while ($data = mysql_fetch_row($result)) { 
            }
            ?>
            <tbody>
                <tr>
                    <td align="center" valign="middle"><?php echo $data['id']; ?></td>
                    <td align="center" valign="middle"><?php echo $data['name']; ?></td>
                    <td align="left" valign="middle"><?php echo $data['surname']; ?></td>
                </tr>    
            </tbody>
        </table>
    </body>
</html>

But i wann't also that the numer of rows in html table depends by number of columns in sql table. 但是我也不想html表中的行数取决于sql表中的列数。 For example in this case i want to display only three rows (three columns in sql table). 例如,在这种情况下,我只想显示三行(sql表中的三列)。 When i add the column's to sql table i want to rows in html output table increses dynamicly. 当我将列添加到sql表时,我希望html输出表中的行动态增加。

Could someone help me with this code ? 有人可以帮我这个代码吗?

Change your code to this: 将代码更改为此:

<tbody>
    <?php
    $result = mysql_query($select_data);
    while ($data = mysql_fetch_row($result)) {
        ?>
        <tr>
            <td align="center" valign="middle"><?php echo $data['id']; ?></td>
            <td align="center" valign="middle"><?php echo $data['name']; ?></td>
            <td align="left" valign="middle"><?php echo $data['surname']; ?></td>
        </tr>
        <?php
    }
    ?>
</tbody>

You are closing your while loop before displaying the results 您正在关闭while循环,然后再显示结果

You close your while-loop not correct: 您关闭while循环不正确:

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html">
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
            <thead>
                <tr>
                    <th align="left" valign="middle">id</th>
                    <th align="center" valign="middle">name</th>
                    <th align="center" valign="middle">surname</th>                    
                </tr>
            </thead>
            <tbody>
            <?php while ($data = mysql_fetch_row($result)):?>
                <tr>
                    <td align="center" valign="middle"><?php echo $data['id']; ?></td>
                    <td align="center" valign="middle"><?php echo $data['name']; ?></td>
                    <td align="left" valign="middle"><?php echo $data['surname']; ?></td>
                </tr>
            <?php endwhile;?>
            </tbody>
        </table>
    </body>
</html>

Using the the "while(cond):" and "endwhile;" 使用“ while(cond):”和“ endwhile;” command you can see better where something starts and where it ends than using the encapsulation with braces. 命令比使用带有大括号的封装更好地看到了东西的起点和终点。

Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli , since mysql is not anymore actively supported. 请考虑将数据库包装程序从mysql_切换到PDOmysqli ,因为不再积极支持mysql。

You could also use instead: 您还可以改用:

<?php echo $data['id']?>

rather the shortform: 简称:

<?=$data['id']?>

Which is also avaiable w/o php short open after 5.3 (I think it was 5.3) 在5.3之后,也可以不带php短打开(我认为是5.3)

If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. 如果我正确理解您的问题,则希望返回的行数与表dane中的列数匹配。 The following code should do just that and I'm using mysqli which I strongly recommend. 下面的代码应该做到这一点,我强烈建议使用mysqli。 The mysql_query extension is deprecated as of PHP 5.5.0. 从PHP 5.5.0开始不推荐使用mysql_query扩展名。

<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table

// Let's make sure we could establish a connection
if($db->connect_errno > 0){
    die('Unable to connect to the database ' . $db->connect_error);
}

// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";


if(!$result = $db->query($select_cols)){
    die('There was an error running the query.');
}

while($row = $result->fetch_assoc()){
    $cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}

// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);

// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows"; 

if(!$result = $db->query($select_data)){
    die('There was an error running the query ' . $db->error);
}

while($row = $result->fetch_assoc()){
    $data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html">
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
            <thead>
                <tr>
                    <?php foreach ($cols as $k) : // Loop through columns ?>
                    <th align="center" valign="middle"><?php echo $k; ?></th>
                    <?php endforeach; ?>                  
                </tr>
            </thead>
            <tbody>

                    <?php foreach ($data as $k) : // Loop through each $data array() ?>
                    <tr>
                        <?php foreach ($k as $v) : // Let's display the records ?>
                        <td align="center" valign="middle"><?php echo $v; ?></td>
                        <?php endforeach; ?>
                    </tr>
                    <?php endforeach; ?>

            </tbody>
        </table>
    </body>
</html>

I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. 我还自由地将列名动态显示为表标题,这将消除在列增加时稍后手动添加它们的需要。 If you would like to manually create them simply replace the top php portion with this one: 如果您想手动创建它们,只需用以下内容替换顶部的php部分:

<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table

// Let's make sure we could establish a connection
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";


if(!$num_cols = $db->query($select_cols)){
    die('There was an error running the query.');
}

$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows"; 

if(!$result = $db->query($select_data)){
    die('There was an error running the query [' . $db->error . ']');
}

while($row = $result->fetch_assoc()){
    $data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection

// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>

and adjust the html code between <thead></thead> . 并调整<thead></thead>之间的html代码。 This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. 整个样本很快就放在一起了,因此可以根据需要进行改进和调整。 Please inspect it for any typos as well. 请检查是否有错字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM