繁体   English   中英

在网页上的 HTML 表中显示 MySQL 数据库表中的值

[英]Show values from a MySQL database table inside a HTML table on a webpage

我想从数据库表中检索值并将它们显示在页面的 html 表中。 我已经搜索过这个,但我找不到答案,虽然这肯定很简单(这应该是数据库的基础知识,哈哈)。 我想我搜索的术语具有误导性。 数据库表名是tickets,它现在有6个字段(submission_id、formID、IP、name、email和message),但应该有另一个字段叫ticket_number。 我怎样才能让它在 html 表中显示来自数据库的所有值,如下所示:

<table border="1">
  <tr>
    <th>Submission ID</th>
    <th>Form ID</th>
    <th>IP</th>
    <th>Name</th>
    <th>E-mail</th>
    <th>Message</th>
  </tr>
  <tr>
    <td>123456789</td>
    <td>12345</td>
    <td>123.555.789</td>
    <td>John Johnny</td>
    <td>johnny@example.com</td>
    <td>This is the message John sent you</td>
  </tr>
</table>

然后是“john”以下的所有其他值。

取自 W3Schools 的示例: PHP 从 MySQL 中选择数据

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

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

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

是个学习的好地方!

试试这个:(完全动态...)

<?php
$host    = "localhost";
$user    = "username_here";
$pass    = "password_here";
$db_name = "database_name_here";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}

//get results from database
$result = mysqli_query($connection,"SELECT * FROM products");
$all_property = array();  //declare an array for saving property

//showing property
echo '<table class="data-table">
        <tr class="data-heading">';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '<td>' . $property->name . '</td>';  //get field name for header
    array_push($all_property, $property->name);  //save those to array
}
echo '</tr>'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    foreach ($all_property as $item) {
        echo '<td>' . $row[$item] . '</td>'; //get items using property value
    }
    echo '</tr>';
}
echo "</table>";
?>

面向对象的 PHP/5.6.25 和 MySQL/5.7.17 使用 MySQLi [动态]

在 PHP.net 上了解有关 PHP 和 MySQLi 库的更多信息

首先,启动与数据库的连接。 为此,创建连接所需的所有字符串变量,调整它们以适应您的环境,然后使用new mysqli()创建一个新的连接对象,并使用先前创建的变量作为其参数对其进行初始化。 现在,检查连接是否有错误并显示一条消息,无论是否发现任何错误。 像这样:

<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>

接下来,创建一个将查询保存为字符串的变量,在这种情况下,它是一个select语句, limit为 100 条记录以保持列表较小。 然后,我们可以通过从我们的连接对象调用mysqli::query()函数来执行它。 现在,是时候显示一些数据了。 首先通过echo打开一个<table>标签,然后使用mysqli::fetch_row()以数值数组的形式一次获取一行,然后可以用简单的 for 循环显示。 mysqli::field_count应该是不言自明的。 不要忘记对每个值使用<td></td> ,并使用echo"<tr>"echo"</tr>打开和关闭每一行。最后我们关闭表,连接为很好用mysqli::close()

<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
    echo "<tr>";
    for($i = 0; $i < $queryResult->field_count; $i++){
        echo "<td>$queryRow[$i]</td>";
    }
    echo "</tr>";
}
echo "</table>";
$conn->close();
?>

首先,连接到数据库:

$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);

您可以使用它来显示单个记录:

例如,如果 URL 是/index.php?sequence=123 ,下面的代码将从表中选择,其中 sequence = 123

<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);

echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>

或者,如果要在表中列出与条件匹配的所有值:

<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>

当然更好的解决方案是动态的,这样它就可以用于任何查询而无需知道列名?

如果是这样,试试这个(显然查询应该匹配你的数据库):

// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);

// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");

// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);

// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
    echo '<td>';
    echo $key;
    echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
    echo '<tr>';
    foreach($row as $column) {
        echo '<td>';
        echo $column;
        echo '</td>';
    }
    echo '</tr>';
}
echo '</table>';

取自这里: https : //www.antropy.co.uk/blog/handy-php-snippets/

这是使用 PDO 从 MySQL 数据库获取数据的简单方法。

define("DB_HOST", "localhost");    // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");

$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);

$print = ""; // assign an empty string

$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);

$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';

while ($names = $stmt->fetch()) { // loop and display data
    $print .= '<tr>';
    $print .= "<td>{$names->firstname}</td>";
    $print .= "<td>{$names->lastname}</td>";
    $print .= '</tr>';
}

$print .= "</table>";
echo $print;
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=@mysql_num_rows($query);

echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";

for($i=0 ,$i<$y,$i++)
{
  $values=mysql_field_name($query,$i);
  echo "<th>$values</th>";
}

echo "</tr>";

while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
  print("<tr>\n".
  "<td>$p</td>".
  "</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user     = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd             = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database

$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()

echo '<table border=1px>';  // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers

while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}

echo '</table>';  //closing table tag
?>

它会像这样打印表格,只需逐行阅读,以便您轻松理解它。

<div class="container" style="margin-top:2em;margin-bottom:33em;">
  <table border="1" class="table table-striped" style="margin-top: 2em;">
    <thead>
      <tr>
        <th>No.</th>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
    </thead>
    <tbody>
    <?php
    // ini_set('display_errors', 1);
    // ini_set('display_startup_errors', 1);
    // error_reporting(E_ALL);
    $servername="localhost";
    $username="jaipuror_order"; 
    $password="EEfaM?8$8tpy";
    //!@#$%^&*(
    $db="jaipuror_order";

    $conn=mysqli_connect($servername,$username,$password,$db);
    //mysql_select_db($db);  
    if (!$conn) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
        exit;
    }
    @session_start();
      $result = $conn->prepare("SELECT customer_id, first_name, last_name FROM customer");
      $result->execute();
      for($i=0; $row = $result->fetch(); $i++){
    ?>
      <tr>
        <td><label><?php echo $row['customer_id']; ?></label></td>
        <td><label><?php echo $row['first_name']; ?></label></td>
        <td><label><?php echo $row['last_name']; ?></label></td>
      </tr>
      <?php } ?>
    </tbody>
  </table>
</div>
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
     border: 1px solid black;
}
</style>
</head>
<center>
<body>

<?php

$con = mysql_connect("localhost","root","");
mysql_select_db("rachna",$con);



$query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'A' GROUP BY Iyear";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
     echo "<table><tr><th></th><th>1999</th><th>2000</th><th>2001</th><th>2003</th></tr>";
     echo "<th>A</th>"; 

     //Code for A Customer-------------------------------------------
     while($row =mysql_fetch_array($result)) {
         echo "<th>" . $row['RESULT'] . "</th>";
         }

          echo"<tr></tr>";  

           //COde of B Customer--------------------------------------

         echo "<th>B</th>";
     $query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'B' GROUP BY Iyear";
    $result1 = mysql_query($query) or die(mysql_error());


     while($row = mysql_fetch_array($result1)) {
         echo "<th> " . $row["RESULT"]. "</th>";
     }
     echo "</table>";
} else {
     echo "0 results";
}


?>  
</center>
</body>
</html>

OOP 风格:首先与数据库连接。

<?php
class database
{

 public $host = "localhost";
 public $user = "root";
 public $pass = "";
 public $db   = "db";
 public $link;

 public function __construct()
 {
    $this->connect();
 }

 private function connect()
 {
   $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->link;
 }

 public function select($query)
 {
    $result = $this->link->query($query) or die($this->link->error.__LINE__);

    if($result->num_rows>0)
    {
      return $result;
    } 
    else 
    {
      return false;
    }
}
?>

然后:

    <?php
        $db = new database();

        $query = "select * from data";
        $result = $db->select($query);

        echo "<table>";
         echo "<tr>";
            echo "<th>Name </th>";
            echo "<th>Roll </th>";
         echo "</tr>";
         while($row = mysqli_fetch_array($result)) 
         {
            echo "<tr>";
            echo "<td> $row[name]</td>";
            echo "<td> $row[roll]</td>";
            echo "</tr>";
         }
       echo "</table>";
 ?>

暂无
暂无

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

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