I'm currently working on a php script and stuck at this part. I have a database table which I want to display information from each row. I have two dropdown menus which I want to have the exact same names with just with a different url. I'm assuming this is possible, and I'm doing something wrong, as I'm not that advanced with php.
I found this question that was similar but didn't seem to see anything that helped much.
Use same foreach multiple times
Here is what I currently have
Top of page
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
$header = "SELECT id, location FROM table";
try
{
$headerstmt = $db->prepare($header);
$headerstmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
?>
Then here is the section with the foreach loops
<ul class="nav navbar-nav">
<li class="dropdown <?php if ($page == 'view') {echo 'active';} ?>">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">View <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php foreach ($headerstmt->fetchAll() as $hrow) { ?>
<li><a href="view.php?id=<?php echo $hrow['id'] ?>"><?php echo $hrow['location']; ?></a></li>
<?php } ?>
</ul>
</li>
<li class="dropdown <?php if ($page == 'edit') {echo 'active';} ?>">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Edit <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php foreach ($headerstmt->fetchAll() as $hrow) { ?>
<li><a href="edit.php?id=<?php echo $hrow['id'] ?>"><?php echo $hrow['location']; ?></a></li>
<?php } ?>
</ul>
</li>
</ul>
The first foreach loop works correctly, however the second one is blank.
Thanks in advance if anyone is able help.
You should store the result of $headerstmt->fetchAll()
in a variable and then use the resulting variable for the foreach loops.
$results = $headerstmt->fetchAll();
foreach( $results as $row ) {
}
foreach( $results as $row ) {
}
foreach( $results as $row ) {
}
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.