I am a php noob and am having a hard time figuring out something that seems like it should be quite simple. My main goal here is to get ALL numbers found in column "number" and then list numbers 01-20 as long as they DON'T show up in the database.
Here is what I have so far:
$select = mysqli_query($connect, "SELECT * FROM `memfav`");
while($row=mysqli_fetch_assoc($select)) {
$number = $row['number'];
}
for($i=1; $i<=20; $i++) {
if($i<>$number) {
if($i<10) {
echo "<option value=\"$i\">0$i</option>";
}
else{
echo "<option value=\"$i\">$i</option>";
}
}
}
However, It's only not showing the latest entry. Am I completely missing something?
ETA: For anybody who is looking for something similar, I finally figured out a way to achieve this! (with the help from someone else)
$select = mysqli_query($connect, "SELECT `number` FROM `memfav`");
while( $row = mysqli_fetch_assoc($select) ) {
$numbers[] = $row['number'];
}
for($i=1; $i<=20; $i++) {
if( !in_array($i, $numbers) ) {
echo '<option value="$i">' . str_pad($i, 2, '0', STR_PAD_LEFT) . '</option>';
}
}
You have placed your comparison logic outside of your while
loop; As written, your code loops through your mysql results and sets $number
to a new value for each row. This loop completes, leaving $number
equal to the value from the last row returned. Then it checks the final value of $number
against the values 1-20. To fix this, place the comparison logic inside the while
loop.
$select = mysqli_query($connect, "SELECT * FROM `memfav`");
while($row=mysqli_fetch_assoc($select)) {
$number = $row['number'];
for($i=1; $i<=20; $i++) {
if($i<>$number) {
if($i<10) {
echo "<option value=\"$i\">0$i</option>";
}
else{
echo "<option value=\"$i\">$i</option>";
}
}
}
}
Try this:
$numbers = array();
for ($i = 1; $i <= 20; $i++) {
if ($i < 10) {
$numbers[] = "0{$i}";
} else {
$numbers[] = "{$i}";
}
}
$select = mysqli_query($connect, "SELECT * FROM memfav");
$usedNumbers = array();
while ($row = mysqli_fetch_assoc($select)) {
$usedNumbers[] = $row['number'];
}
$diff = array_diff($numbers, $usedNumbers);
foreach ($diff as $key => $value) {
echo "<option value=\"{$value}\">{$value}</option>";
}