简体   繁体   中英

Printing an array in php from mysql

Just trying to do a tutorial from a few weeks ago and run into a bit of trouble.

I'm trying to retrieve all the data from an array inside of mysql. Here's my code so far, which kinda works.

include('db_conn.php'); //db connection


$query = "SELECT * FROM kit202_product";
$result = $mysqli->query($query);

while ($row = mysqli_fetch_array($result) )
{

    printf("%s %s %d %s\n", $row[0], $row[1],$row[2], $row[3]); 
}

The table is meant to look like this 在此处输入图片说明

While the code does work (it prints out every value), How do I organize it so it looks like that in the picture? I'm guessing I need to print into a table somehow?

Googling hasn't really gotten me anywhere. Only really shown be how to print one line of the array.

You could do it in a table by looping your results inside the <tr>s

<?php 
include('db_conn.php'); //db connection


$query = "SELECT * FROM kit202_product";
$result = $mysqli->query($query);
?>
<h1>Search Product Details</h1>
<table>
<thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Price</th>
        <th>Description</th>
    </tr>
</thead>
<tbody>
    <?php
    while ($row = mysqli_fetch_array($result) )
    {
    ?>
    <tr>
        <?php 
        echo "<td>" . $row[0] . "</td>";
        echo "<td>" . $row[1] . "</td>";
        echo "<td>" . $row[2] . "</td>";
        echo "<td>" . $row[3] . "</td>";
        ?>
    </tr>
    <?php
    }
    ?>
</tbody>
</table>
include('db_conn.php'); //db connection


$query = "SELECT * FROM kit202_product";
$result = $mysqli->query($query);

echo "<table>";
echo "<tr>";
    echo "<th>ID</th>";
    echo "<th>Name</th>";
    echo "<th>Price</th>";
    echo "<th>Description</th>";
echo "</tr>";
    while ($row = mysqli_fetch_array($result) )
    {
    echo "<tr>";
        echo "<td>".$row[0]."</td>";
        echo "<td>".$row[1]."</td>";
        echo "<td>".$row[2]."</td>";
        echo "<td>".$row[3]."</td>"; 
    echo "</tr>";
    }
echo "</table>";

Design your table with CSS

<?php
include('db_conn.php'); //db connection


$query = "SELECT * FROM kit202_product";
$result = $mysqli->query($query);
?>
<TABLE BORDER="5"    WIDTH="50%"   CELLPADDING="4" CELLSPACING="3">
   <TR>
      <TH COLSPAN="2"><BR><H3>Search Product Detail</H3>
      </TH>
   </TR>
   <TR>
      <TH>ID</TH>
      <TH>Name</TH>
      <TH>Price</TH>
      <TH>Description</TH>
   </TR>
<?php 
while ($row = mysqli_fetch_array($result) )
{
    echo "<TR ALIGN='CENTER'>
      <TD>$row[0]</TD>
      <TD>$row[1]</TD>
      <TD>$row[2]</TD>
      <TD>$row[3]</TD>
   </TR>"; 
}

?>

</TABLE>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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