web-dev-qa-db-fra.com

Afficher les valeurs d'une table de base de données MySQL dans une table HTML sur une page Web

Je veux récupérer les valeurs d'une table de base de données et les afficher dans une table html d'une page ... J'ai déjà recherché cela, mais je n'ai pas trouvé de réponse, même si c'est quelque chose de facile (ce devrait être l'essentiel des bases de données lol). Je suppose que les termes que j'ai recherchés sont trompeurs… .. Le nom de la table de la base de données est des tickets, il contient actuellement 6 champs (ID_substance, ID_formulaire, IP, nom, email et message), mais devrait avoir un autre champ appelé ticket_number ..__ Comment puis-je l'obtenir pour afficher toutes les valeurs de la base de données dans un tableau html comme ceci:

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

Et puis toutes les autres valeurs en dessous de 'john'.

36
Alex

Exemple tiré de W3Schools: PHP Sélectionnez des données dans 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);
?>

C'est un bon endroit pour apprendre!

72
Jonnny

Essayez ceci: (Complètement dynamique ...)

<?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
waLL e

Tout d'abord, connectez-vous à la base de données:

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

Vous pouvez utiliser ceci pour afficher un seul enregistrement:

Par exemple, si l'URL était /index.php?sequence=123, le code ci-dessous sélectionnerait dans le tableau où la séquence = 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, si vous souhaitez répertorier toutes les valeurs correspondant aux critères dans un tableau:

<?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
charlie
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
user5689669

Orienté objet avec PHP/5.6.25 et MySQL/5.7.17 avec MySQLi [Dynamic]

En savoir plus sur PHP et la bibliothèque MySQLi sur PHP.net.

Commencez par vous connecter à la base de données. Pour ce faire, créez toutes les variables de chaîne nécessaires à la connexion, ajustez-les en fonction de votre environnement, puis créez un nouvel objet de connexion avec new mysqli() et initialisez-le avec les paramètres précédemment définis. À présent, vérifiez si la connexion contient des erreurs et affichez un message pour indiquer si vous en avez trouvé ou non. Comme ça:

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

Ensuite, créez une variable qui contiendra la requête sous forme de chaîne. Dans ce cas, il s’agit d’une instruction select avec une limit de 100 enregistrements pour que la liste reste petite. Ensuite, nous pouvons l'exécuter en appelant la fonction mysqli::query() à partir de notre objet de connexion. Maintenant, il est temps d'afficher certaines données. Commencez par ouvrir une balise <table> à travers echo, puis extrayez une ligne à la fois sous la forme d'un tableau numérique avec mysqli::fetch_row() qui peut ensuite être affiché avec une simple boucle for. mysqli::field_count devrait être explicite. N'oubliez pas d'utiliser <td></td> pour chaque valeur et d'ouvrir et de fermer chaque ligne avec echo"<tr>" et echo"</tr>. Enfin, nous fermons la table et la connexion avec 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();
?>

Tout retour serait apprécié! Bonne chance!

2
Arturo Lozano
<?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
?>

il imprimerait le tableau comme ceci il suffit de le lire ligne par ligne pour que vous puissiez le comprendre facilement ..

1
Ram

Voici un moyen facile d'extraire des données d'une base de données MySQL à l'aide de PDO.

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
Ali Abdul
<!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
MD Shahrouq
<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
user8029840

OOP Style: À la première connexion avec la base de données.

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

Ensuite :

    <?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
rashedcs