Question

I have 2 relationship tables in my database.

I have been trying to get my head round the below.

I have contact table, and i have an order table.

I want to try and display the contact info (name, email etc) once, and then display the order information.

I know I can do that with:

<?php 
  $query = $db->prepare("SELECT *
                     FROM contact 
             WHERE type = ? 
             ORDER BY date") 
             or die(mysqli_error($db));  
  $type = "order";
  $query->bind_param('s', $type);
  $query->execute(); 
  $query->store_result(); 
  $query->bind_result($id, $name, $email, $date); 

  while ($query->fetch()) {
     $date = strtotime($date); 
     $date = date("F jS  Y", $date);
?>


From: <?php echo $name ?>

<input type="Checkbox" name="checkbox[]"  id="checkbox[]"value="<? echo $contactid; ?>">

<p>
<?php 
   echo $comments 
?>
</p>

<?php 
     echo $date ;
?>

<?php
     $order = $db->prepare("SELECT title, number
             FROM preorder 
             WHERE id = ? ") 
             or die(mysqli_error($db));  

     $order->bind_param('s', $id);
     $order->execute(); 
     $order->store_result(); 
     $order->bind_result( $title, $number ); 

     while ($order->fetch()) {
        echo $title, $number ; 
     }  
   } 
?>

That works fine, but feels wrong, and easier way to do it without doing 2 selects. I want to then display the orders, within that loop, so the name, email, etc is not repeated with each order.

Was it helpful?

Solution

I would solve it with a left join like this:

<?php
  $query = $db->prepare(
    "SELECT *, preorder.title, preorder.number " .
    "FROM contact " .
    "LEFT JOIN preorder  ON (contact.contactid = preorder.contactid) " .
    "WHERE type = ? ORDER BY contactid, date")
  or die(mysqli_error($db));
  $type = "order";
  $query->bind_param('s', $type);
  $query->execute();
  $query->store_result();
  $query->bind_result($id, $name, $email, $date, $title, $number);

  $last_id = false;
  while ($query->fetch()) {
    $date = strtotime($date);
    $date = date("F jS  Y", $date);

    if ($contactid != $last_id) {
?>
        From: <?php echo $name ?>
        <input type="Checkbox" name="checkbox[]" 
               id="checkbox[]" value="<? echo $contactid; ?>"> 
        <p>
            <?php
            echo $comments
            ?>
        </p>
<?php
      echo $date;
    }
    echo $title, $number;
    $last_id = $contactid;
  }
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top