I have a database where plots (spots/places) are saved (this can be 5, 40 ,91 etc. (not incremented)) On my website I have a dropdown option where available plots are selected (0 - 1023). I want the option that is found in the database to be hidden from the dropdown selection on the website. So if plot 1 is taken it is found in the database and it shouldn't be available in the website dropdown selection. I can't seem to get this working...
This is the code that I came up with.
<label for="plotnumber">Plotnumber :</label></br>
<select name="input_plotnumber">
<?php for ($i = 0; $i <= 1023; $i++) : ?>
$query = ("SELECT plotnumber FROM plot1");
$result = $conn->query($query);
$arrayofplots = mysqli_fetch_all($result);
if (in_array($i, $arrayofplots)) {
}
else {
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
}
<?php endfor; ?>?>
</select>
If you modify the SQL to select all taken plots you can then decide to only output option
elements whose value is not within that recordset. Based upon your comment that there is a column taken
you might try like this:
<label>Plotnumber :
<br />
<?php
$sql='select plotnumber from plot1 where taken=1';
$res=$conn->query($sql);
$data=$res->fetch_all(MYSQLI_ASSOC);
?>
<select name="input_plotnumber">
<option selected disabled hidden>Select Plot
<?php
for( $i=0; $i < 1024; $i++ ){
if( !in_array( $i, array_column($data,'plotnumber') ) )printf('<option>%d',$i);
}
?>
</select>
</label>
mysqli_fetch_all
into a one-dimensional array before you can use in_array
.WHERE
clause. I have used taken=1
but if you have a string like taken/not taken
then modify it accordingly.$result->fetch_all()
or procedural mysqi_fetch_all()
, instead of mixing both.Updated code:
<?php
$query = "SELECT plotnumber FROM plot1 WHERE taken=1";
$result = $conn->query($query);
$arrayofplots = $result->fetch_all();
// convert to a 1d array
$arrayofplots = array_map(function($row){
return $row[0];
}, $arrayofplots);
?>
<label for="plotnumber">Plotnumber :</label></br>
<select name="input_plotnumber">
<?php
for ($i = 0; $i <= 1023; $i++){
if (!in_array($i, $arrayofplots)) {
echo '<option value="' . $i . '">' . $i . '</option>';
}
}
?>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.