Question

When I'm trying to call this script it first shows me to chose one.
Then I can chose from 8417 - 8422, just like in the where clause.
But If I pick 8417, it shows me the data for that id but shows me 8418 as selected.
After that 8417 isn't anymore in the dropbox! Then it only goes from 8418 to 8422.

I can't find the mistake. Does anyone have any tipps?

$strSql= "SELECT id FROM tbl_person where id between 8417 and 8422";
$result = mysqli_query($conn,$strSql) or die('Error generating Dropdown: '. mysqli_connect_error());

echo '<form><select size="1" name="ddKfz" class="dropID" onchange="ddChange(this.form)">';
$rs = mysqli_fetch_array($result);
if (empty($rs)) {
    echo  "<option selected value='0' style='color:#cc0000'>Empty!</option>";
} else {
    if ($_REQUEST["ddKfz"]=="" or $_REQUEST["ddKfz"]==0 ) {
        echo  "<option selected value='0' style='color:#cc0000'>Please pick one:</option>";
        mysqli_data_seek($result, 0);
    }
    while ($rs = mysqli_fetch_array($result)) {
        $strOption= "Kfz: " . $rs["id"];
        if ($_REQUEST["ddKfz"]==$rs["id"])
            echo  "<option value='" . $rs["id"] . "'selected style='color:red'>" . $strOption . "</option>";
        else
            echo  "<option value='" . $rs["id"] . "' >" . $strOption . "</option>";  
    }
}
echo "</select></form>";
mysqli_free_result($result);

The function called by the Dropdown on Change

function ddChange(f) {
    f.method="post";
    f.action="index.php";
    f.submit();
}
Was it helpful?

Solution

Don't do $rs = mysqli_fetch_array($result); on top. This already reads out the first row (8417). Instead use $result->num_rows:

echo '<form><select size="1" name="ddKfz" class="dropID" onchange="ddChange(this.form)">';
if($result->num_rows < 1) {
    echo  "<option selected value='0' style='color:#cc0000'>Empty!</option>";
    …

A few extra points to consider:

  • Don't use $_REQUEST, use $_POST instead, and sanitize the data!
  • You don't need mysqli_data_seek($result, 0); -value='" . $rs["id"] . "'selected is missing a space before selected (this might be why 8417 doesn't show up in the browser anymore)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top