1

I have a problem with my PHP code saying that

"Notice: Undefined index"

since I am a beginner i am not getting well what is wrong exactly so please help me.

<?php 
    require_once 'core/init.php';
    $id = $_POST['id'];
    $id =(int)$id; 

    $sql ="SELECT * FROM products WHERE id = '$id'";
    $result = $db->query($sql);
    $product= mysqli_fetch_assoc($result);

    $brand_id = $product['brand'];
    $sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
    $brand_query = $db->query($sql);
    $brand = mysqli_fetch_assoc($brand_query); 
?>

//index.php

<?php 
      require_once 'core/init.php';
      include 'includes/head.php';
      include 'includes/navigation.php';
      include 'includes/headerfull.php';
      include 'includes/leftbar.php';
      include 'includes/footer.php';      
      include 'includes/detailsmodal.php';

      $sql = "SELECT * FROM products WHERE featured = 1";
      $featured = $db->query($sql);
?>
        <!--main content-->
        <div class="col-md-8">          
        <div class="row">
        <h2 class="text-center">Feature products</h2>
        <?php while($product = mysqli_fetch_assoc($featured)) : ?>
        <div class="col-md-3 text-center"> 
            <h4><?= $product['title']; ?> </h4>
            <img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>" class="img-thumb" />
            <p class="list-price text-danger">List price:<s>$<?= $product['list_price']; ?></s></p>
            <p class="price">Our price :$<?= $product['price']; ?></p>
        <button type="button" class="btn btn-sm btn-success" onclick="detailsmodal(<?= $product['id']; ?>)">Details</button>
        </div>

        <?php endwhile ;?>
        </div>
    <footer class="text-center" id="footer">&copy; copyright 2019</footer>

     </div>     

    <?php 
        include 'includes/rightsidebar.php';
        include 'includes/footer.php';

    ?>

Undefined index: id in C:\xampp\htdocs\tutorial\includes\detailsmodal.php on line 3

  • 1
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Martijn May 27 '19 at 10:44
  • Your code is vulnerable to SQL injection. You should use prepared statements. – Dharman May 27 '19 at 11:55

1 Answers1

1

in detailsmodal.php file index $_POST['id'] is not defined

first check if is set do job ....

if(isset($_POST['id'])){
   code...
}else{
   code...
}

or

$id = isset($_POST['id']) ? $_POST['id'] : null;
Mehdi Daalvand
  • 631
  • 7
  • 14