I am currently creating a menu item and for the most part, it works but the information pulled is not correct for the 2nd level submenu(letters). I have tried so many different joins but either only pulls one of my submenu items or all of them. Not sure what I need to change at this point to make it work and not sure how to better explain the issue.
As for my Tables
menu : columns id, name
people : id, people_name, href, menu_id
letters : id, letters_names, href, people_id
My code is here:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=menu",'root','');
} catch (PDOException $ex) {
echo $ex->getMessag();
}
$sql = "SELECT * FROM menu ORDER BY id";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Kayla Lindstrom">
<title>Lindstrom Letters</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<div id="page">
<ul>
<?php while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$sub_sql = "SELECT * FROM people WHERE menu_id=:id";
$sub_stmt = $pdo->prepare($sub_sql);
$sub_stmt->bindParam(':id', $row->id,PDO::PARAM_INT);
$sub_stmt->execute();
?>
<li><a href=""><?php echo $row->name; ?></a>
<?php if($sub_stmt->rowCount()){ ?>
<ul>
<?php while($sub_row = $sub_stmt->fetch(PDO::FETCH_OBJ)) {
$sub2_sql = "SELECT * FROM letters WHERE people_id=:id"; /*Here is where I am stuck.*/
$sub2_stmt = $pdo->prepare($sub2_sql);
$sub2_stmt->bindParam(':id', $row->id,PDO::PARAM_INT);/*and here*/
$sub2_stmt->execute(); ?>
<li><a href="<?php echo $sub_row->href; ?>">
<?php echo $sub_row->people_name;?></a>
<?php if($sub2_stmt->rowCount()){ ?>
<ul>
<?php while($sub2_row = $sub2_stmt->fetch(PDO::FETCH_OBJ)) { ?>
<li><a href="<?php echo $sub2_row->href; ?>">
<?php echo $sub2_row->letters_name;?></a></li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
In your approach your are doing one mistake, i guess,
Instead of this:
$sub2_stmt->bindParam(':id', $row->id,PDO::PARAM_INT);/*and here*/
Try:
$sub2_stmt->bindParam(':id', $sub_row->id,PDO::PARAM_INT);/*and here*/
And it should work. But you can achieve this by inner join, and with one query you can join all the tables. Query should be like:
SELECT l.href, l.letters_name FROM menu m INNER JOIN people p ON m.id = p.menu_id INNER JOIN letters l ON l.people_id = p.id;
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.