0
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$yearHTML = '';
$yearHTML .= '<select name="year" id="yearDrop">'.PHP_EOL; 
$yearHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
foreach ($years as $year) {
    if (!$validSubmission && isset($_POST['year']) && $year == $_POST['year'])
    {
        $yearHTML .= "<option value='".$year."' selected='selected'>$year</option>".PHP_EOL;
    }
    else
    {
        $yearHTML .= "<option value='".$year."'>$year</option>".PHP_EOL;
    }
}

$yearHTML .= '</select>'; 

上面我有一个下拉菜单,其中包含下拉菜单中的选项 1 - 10。我遇到的问题是,无论我从下拉菜单中选择哪个数字,它都会一直1在数据库中插入数字。任何人都可以在下面的代码中看到为什么这样做:

$getyear = in_array($_POST['year'], $years);

    $insertsql = "
    INSERT INTO Student
    (Year)
    VALUES
    (?)
    ";
    if (!$insert = $mysqli->prepare($insertsql)) {
    // Handle errors with prepare operation here
    }                                           

    $insert->bind_param("i", $getyear);

    $insert->execute();

    if ($insert->errno) {
    // Handle query error here
    }

    $insert->close();
4

1 回答 1

5
$getyear = in_array($_POST['year'], $years);

返回真。True 被强制转换为 INT,因此变为 1;

替换为:

if( in_array($_POST['year'], $years) === true ){
  $getyear = (int) $_POST['year'];
}
于 2012-11-26T19:41:20.197 回答