slamek10 slamek10 - 5 months ago 15
PHP Question

Making table in PHP from database

I have a database called clanovi (members in englsih) which has stored name, surname, adress, email and gender of members. What I am trying to do is make a table from this data from database.

Here is my code https://jsfiddle.net/9j34xfwx/2/

<body>
<?php
require_once("Konekcija.php");
error_reporting(0);

mysql_connect("localhost", "root", "");
mysql_select_db("umv");

$sql=mysql_query("SELECT * FROM clanovi ORDER BY rbroj ASC");

$ime='ime';
$prezime='prezime';
$adresa='adresa';
$email='email';
$spol='spol';
?>


<table id='display'>
<?php
while ($rows=mysql_fetch_assoc($sql)){
?>

<tr><td>Ime clana: <?php echo $rows[$ime]; ?></td>
<tr><td>Prezime clana: <?php echo $rows[$prezime]; ?></td>
<tr><td>Adresa clana: <?php echo $rows[$adresa]; ?></td>
<tr><td>Email clana: <?php echo $rows[$email]; ?></td>
<tr><td>Spol clana: <?php echo $rows[$spol]; ?></td>
<?php
}
?>
</table>


Here is photo of my web page when it lists all members
from database http://pho.to/ACgD1

enter image description here

My question is, how can I make a table so members name, surname, adress, email and gender are in columns, and beneath are the data from database. As you can see on the photo, my code adds one member beneath another member.

Answer

I assume that you don't need to repeat the text like "Ime clana:" (say label) in each Iteration, and set it as column header, cause that's the exact problem that the HTML <table> is designed to solve. Also if you need the label data to be redundant, then you must be defeating the purpose of using a table, IMHO.

You need to do something like this..

<table id='display'>
 <tr>
  <th>Ime clana:</th>
  <th>Prezime clana:</th>
  <th>Adresa clana:</th>
  <th>Email clana:</th>
  <th>Spol clana:</th>
 </tr>
 <?php
 while ($rows=mysql_fetch_assoc($sql)){
 ?>
 <tr>
  <td><?php echo $rows[$ime]; ?></td>
  <td><?php echo $rows[$prezime]; ?></td>
  <td><?php echo $rows[$adresa]; ?></td>
  <td><?php echo $rows[$email]; ?></td>
  <td><?php echo $rows[$spol]; ?></td></tr>
 <?php  
 }
 ?>
</table>   
Comments