I want to design a menu dynamically with php and msqli. Where I get the menu and submenu. to the drale click that sends me to an appendix called products. php and I display the products of my menu. And if there is a submenu that shows me the sub-products of my category. I have the following code:
<?php
$servername="localhost";
$username="root";
$password="";
$basedatos="menu";
//CREAR CONEXION
$conn=mysqli_connect($servername,$username,$password,$basedatos);
if(!$conn)
{
die("Coneccion fallida". $mysqli_error());
} else
{
echo "Coneccion exitosa\n";
}
function loop_array($array=array(), $parent_id=0){
if(!empty($array[$parent_id])){
echo'<ul>';
foreach($array[$parent_id] as $items){
if($items['parent_id']==3)
{
echo "<li><a href='productos.php?variable=".$items['name']."'/>".$items['name']."</a></li";
}
echo '<li><a href="'.$items['url'].'">';
echo $items['name'];
loop_array($array,$items['id']);
echo '</li></a>';
}
echo'</ul>';
}
}
function display_menus(){
$conn=mysqli_connect("localhost","root","","menu");
$query=$conn->query("SELECT * FROM menus");
$array=array();
if(mysqli_num_rows($query)){
while($rows=mysqli_fetch_array($query)){
$array[$rows['parent_id']][]=$rows;
}
loop_array($array);
}
}
?>
The problem is that I doubled the submenu. One submenu serves and the other does not. This is the file where I receive the selection of products.
<?php
$servername="localhost";
$username="root";
$password="";
$basededatos="menu";
//CREAR CONEXION
$conn=mysqli_connect($servername,$username,$password,$basededatos);
if(!$conn)
{
die("Coneccion fallida.". mysqli_error());
}
{
echo "Coneccion exitosa. \n"."<br>";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
</head>
<body>
<?php
//REcIBIR VARIABLE
$var1=($_GET['variable']);
/*if(empty($var1)){
header('Location:index.php');
}
/*
if (empty($var1))
{
echo "VAriable vacia";
}
else
{
echo "Vaiable con valor";
}
*/
$sql = "SELECT id, modelo FROM productos WHERE parent_id='$var1'";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Modelo: ".$row["modelo"]."<br>";
}}else
{
echo "Sin resultados";
}
echo "Hola";
mysqli_close($conn);
?>
In my database I have two. One of the menus.
id name parent_id url
1 home 0 index.php
2 products 0 producto.php
3 bocina 1
4 rca 1
And the product
id modelo parent_id descripcion
1 ind-3br 3 bocina chica
2 ind-6br 4 rca largo
I wish you could help me.