I am a newbie here and for php too. I am not new to stackoverflow though :)
I am creating a simple reporting system and I want the menues and pages to be generated from the database.
I saw this video on YouTube and managed to create a menu with the following code.
I have a database table called Reports
and columns called rep_id
, rep_date
, rep_ledit_date
, rep_by
, department
, position
, report
, and rep_to
.
So based on the above method, I created a menu using this code.
<?php
require ("includes/db.php");
mysqli_select_db($con, '$db_name');
$sql = "SELECT * FROM reports";
$result = mysqli_query($con, $sql) or die (mysqli_error($con));
$represult=mysqli_fetch_assoc($result);
$rep_by=$represult['rep_by'];
$report=$represult['report'];
?>
<li> Menu
<ul>
<?php do
{
?>
<li><a href="reports.php?rep_id=<?php echo $represult['rep_id']; ?>"> <?php echo $represult['rep_by'] . " (" . $represult['rep_date'] . ")"; ?></a></li>
<?php
} while ($represult=mysqli_fetch_assoc($result));
//$represult['rep_by'];
//$represult['report'];
//$represult['report'] ;
?>
</ul>
</li>
So I created a page called reports.php
to see the details of the content in the database. What I wanted was to see the following rep_by (rep_date) as a heading and report as a content.
I might want to use other columns in the content too. So what kind of code the menu and reports.php
should have to achieve what I want. What I did was the following and it only outputs the first row when all the menu links are clicked.
require ("includes/db.php");
mysqli_select_db($con, '$db_name');
$sql= "SELECT * FROM reports";
$result = mysqli_query($con, $sql) or die (mysqli_error($con));
$represult=mysqli_fetch_assoc($result);
<h1> <?php echo $represult['rep_by'] . " (" . $represult['rep_date'] . ")"; ?></a></h1>
<?php echo $represult['report']; ?>
Your code is a bit confusing due to the mix of PHP tags and HTML so I have reworked it as 100% PHP like this.
The main problem I see in your original code is you are doing this call twice:
One right near
$result = mysqli_query(…)
and the other as the tail end of thedo
/while
loop. Also, unsure of the value of thatdo
/while
loop so I refactored it as a simplewhile
loop. And finally with the restructuring to be 100% PHP I did some formatted concatenation to make it easier to read & see the structure of your overall logic.EDIT: The original poster added additional code saying the problem is it was only returning the first result. The issue—again—is the lack of a
while
loop. Here is my refactored version of that code:report.php:
reports.php (tweaked a bit)