revert
revert

Reputation: 3

Trying to echo out every int that isn't in mysql table with php

I am pretty new at this whole programming stuff. I need to echo out any integer from the mysql database that is missing (in chronological order). So this $row["statement"] has integers starting at 114 and goes to 44714. There are missing numbers in this list, and I need to know which ones. The first number that is missing is 118. So it goes 114, 115, 116, 117, 120, ...

I want to echo 118, 119, and any other missing from this $row["statement"].

What I have here just prints until one is missing, so "114 115 116 117".

<?php 
  $link = mysqli_connect("localhost", "root", "password", "DB")or die("Error " . mysqli_error($link));

  $query = "SELECT statement FROM sales" or die ("Error in the consult.." . mysqli_error($link));
  $result = $link->query($query);
  $count = 114;

  while($row = mysqli_fetch_array($result)) {   
    while ($row["statement"] == $count) {
       echo $count . "<br>";
       $count++;
    }
  }
 ?>

I can't think how to do the reverse. If I were to set the second while conditional to check if !==, this would just print out the entire list, including the missing and not missing. i.e. 114, 115, 116, 117, 118, 119, 120...

Is nesting these whiles bad? Should it be a do while? If statement? I don't get the logic. Please learn me real good.

Upvotes: 0

Views: 60

Answers (2)

revert
revert

Reputation: 3

<?php 
  $link = mysqli_connect("localhost", "root", "password", "DB")or die("Error " . mysqli_error($link));

  $query = "SELECT statement FROM sales" or die ("Error in the consult.." . mysqli_error($link));
  $result = $link->query($query);
  $count = 114;
  $max = 44714;
  $currentNumbers = array();
  $numberOfMissing = 1;

  while($row = mysqli_fetch_array($result)) {   
    array_push($currentNumbers, $row['statement']);
  }

  $tempArray = range($count, $max);
  $missingNumbers = array_diff($tempArray, $currentNumbers);
  foreach ($missingNumbers as $value) {
    echo $numberOfMissing++ . ". " . $value . "<br>";
  }
?>

Thanks Jay!

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

You can make it easy on yourself if make an array and then diff the array -

$count = 114;
$currentNumbers = array();
while($row = mysqli_fetch_array($result)) {
    array_push($currentNumbers, $row['statement'];
}
$tempArray = range($count,max($number));                                           
$missingNumbers = array_diff($tempArray,$CurrentNumbers);
foreach($missingNumber AS $value) {
    echo $value . '<br />';
}

range() array_diff() EXAMPLE

Upvotes: 0

Related Questions