Mostrar os valores de uma tabela de base de dados MySQL dentro de uma tabela HTML numa página web

eu quero recuperar os valores de uma tabela de banco de dados e mostrá-los em uma tabela html em uma página. Eu já procurei por isso, mas eu não consegui encontrar a resposta, embora isso certamente é algo fácil (este deve ser o básico do lol de banco de dados). Acho que os Termos que procurei são enganadores. O nome da tabela de banco de dados é tickets, ele tem 6 campos agora (submission_id, formID, IP, nome, e-mail e mensagem), mas deve ter outro campo chamado ticket_number. Como posso fazê-lo mostrar tudo os valores do db numa tabela html como esta:

<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>[email protected]</td>
    <td>This is the message John sent you</td>
  </tr>
</table>

e depois TODOS os outros valores abaixo de 'João'.

Author: Brian Tompsett - 汤莱恩, 2013-07-28

10 answers

Exemplo retirado do W3Schools: PHP Seleccione os dados do 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);
?>
É um bom lugar para aprender!
 65
Author: Jonnny, 2017-08-09 23:32:37

Tenta isto: (completamente dinâmico...)

<?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>";
?>
 11
Author: waLL e, 2016-10-15 15:11:01
Primeiro, ligue-se à base de dados:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);

Pode usar isto para mostrar um único registo:

Por exemplo, se o URL fosse /index.php?sequence=123, o código abaixo iria selecionar a partir da tabela, onde a sequência = 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>';
?>

Ou, se quiser listar todos os valores que correspondem aos critérios numa tabela:

<?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>';
?>
 4
Author: charlie, 2017-08-09 23:40:54
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");
}
?>
 2
Author: user5689669, 2015-12-17 06:44:46

Orientado a objectos com PHP / 5.6.25 e MySQL/5.7.17 usando MySQLi [dinâmico]

Saiba mais sobre o PHP e a Biblioteca MySQLi em PHP.net.

Primeiro, inicie uma ligação à base de dados. Faça isso fazendo com que todas as variáveis de string necessárias para se conectar, ajustá-las para se ajustar ao seu ambiente, em seguida, criar um novo objeto de conexão com new mysqli() e inicializá-lo com as variáveis previamente feitas como seus parâmetros. Agora, verifique a conexão para erros e exibição uma mensagem se foram encontrados ou não. Assim:

<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
?>

Em seguida, faça uma variável que irá manter a consulta como uma string, neste caso a sua declaração a select com um limit de 100 registos para manter a lista pequena. Então, podemos executá-lo chamando a função mysqli::query() do nosso objeto de conexão. Agora, está na hora de mostrar alguns dados. Comece por abrir uma marca <table> através de echo, obtendo então uma linha de cada vez sob a forma de uma matriz numérica com mysqli::fetch_row() que poderá então ser mostrada com um simples para loop. mysqli::field_count deve ser auto explicativo. Não se esqueça de usar <td></td> para cada valor, e também para abrir e fechar cada linha com echo"<tr>" e echo"</tr>. Finalmente fechamos a mesa, e a conexão também com 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();
?>

Qualquer feedback seria muito apreciado! Boa Sorte!

 2
Author: Arturo Lozano, 2017-08-10 03:59:45
<?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
?>
Iria imprimir a tabela assim. basta ler linha a linha para que você possa entendê-lo facilmente..
 1
Author: Ram, 2013-07-27 22:17:33
<!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>
 0
Author: MD Shahrouq, 2016-10-05 16:55:26

Aqui está uma maneira fácil de obter dados de uma base de dados MySQL usando DOP.

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

try {       // << using Try/Catch() to catch errors!

$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8",DB_USER,DB_PASS);
}catch(PDOException $e){ echo $e->getMessage();}

if($dbc <> true){
    die("<p>There was an error</p>");
}

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

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

if($stmt->execute() <> 0)
{

    $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;
}
 0
Author: Ali Abdul, 2017-08-10 01:39:28

Estilo OOP : Na primeira ligação com a base de dados.

<?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;
    }
}
?>

Depois:

    <?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>";
 ?>
 0
Author: rashedcs, 2017-11-03 20:58:17
<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>
 0
Author: , 2018-04-12 12:25:56