51

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

<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' 下面的所有其他值。

4

9 回答 9

97

取自 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);
?>

是学习的好地方!

于 2013-07-27T21:15:44.203 回答
17

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

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

//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);

//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
    $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>";
于 2016-05-23T20:34:21.973 回答
4

在 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一个包含 100 条记录的语句,limit以保持列表较小。mysqli::query()然后,我们可以通过从我们的连接对象调用函数来执行它。现在,是时候显示一些数据了。首先通过打开一个<table>标签echo,然后以数字数组的形式一次获取一行,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();
?>
于 2017-07-03T21:57:20.847 回答
3

首先,连接数据库:

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

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

例如,如果 URL 是/index.php?sequence=123,下面的代码将从表中选择,其中序列 = 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>';
?>
于 2013-07-27T21:54:30.090 回答
3

这是使用 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;
于 2016-12-16T13:47:20.230 回答
3

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

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

// 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/

于 2019-05-22T12:02:31.783 回答
1
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");
}
?>
于 2015-12-17T06:20:54.877 回答
0
<?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
?>

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

于 2013-07-27T22:09:39.090 回答
-1

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>";
 ?>
于 2017-11-03T20:52:15.180 回答