将 SQL 数据库中的数据显示到 php/html 表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15251095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:54:00  来源:igfitidea点击:

display data from SQL database into php/ html table

phphtmlmysqlphpmyadminxampp

提问by user2108411

OK I have a database on phpmyadmin (sql) and I want to display one of my tables into a table on HTML/PHP. I have searched online and can not implement this feature, so I'm wondering if someone could help me with the coding on this?

好的,我在 phpmyadmin (sql) 上有一个数据库,我想将我的一个表显示到 HTML/PHP 上的表中。我在网上搜索过,无法实现此功能,所以我想知道是否有人可以帮助我进行编码?

database = 'hrmwaitrose'
username = 'root'
host = 'localhost'

NO PW

无密码

I would like to display the data from table name employee

我想显示表名中的数据 employee

回答by Jacob Valenta

You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.

您说您在 PhpMyAdmin 上有一个数据库,因此您使用的是 MySQL。PHP 提供了连接 MySQL 数据库的函数。

$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection

In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.

在 while 循环中(每次遇到结果行时都会运行),我们 echo 创建一个新的表行。我还添加了一个包含字段。

This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.

这是一个非常基本的模板。您会看到使用 mysqli_connect 而不是 mysql_connect 的其他答案。mysqli 代表 mysql 改进。它提供了更好的功能范围。你会注意到它也有点复杂。这取决于你需要什么。

回答by Hyman

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

这是我编写的一个简单函数,用于显示表格数据而无需输入每个列名:(另外,请注意:嵌套循环)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}


UPDATED FUNCTION BELOW

更新功能如下

Hi Hyman,

嗨,Hyman,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

你的函数设计很好,但这个函数总是错过数组中的第一个数据集。我测试过。

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

你的函数非常好,很多人会使用它,但他们总是会错过第一个数据集。这就是我写这个修正案的原因。

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

丢失的数据集由条件 if key === 0 产生。如果 key = 0 只写入列标题,但不写入包含 $key 0 的数据。所以总是缺少数组的第一个数据集。

You can avoid that by moving the if condition above the second foreach loop like this:

您可以通过将 if 条件移动到第二个 foreach 循环之上来避免这种情况,如下所示:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

最好的问候和感谢 - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

以及另一个删除冗余代码块的更新,这些代码块会损害代码的可维护性。

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

}

回答by ka_lin

Look in the manual http://www.php.net/manual/en/mysqli.query.php

查看手册http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

回答by prakashchhetri

refer to http://www.w3schools.com/php/php_mysql_select.asp. If you are a beginner and want to learn, w3schools is a good place.

请参阅http://www.w3schools.com/php/php_mysql_select.asp。如果您是初学者并想学习,w3schools 是个好地方。

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echoit inside your table

你也可以echo在你的桌子里面

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>