gpt4 book ai didi

php - 为什么 isset($_POST {'variable' ]) 即使数组 $_POST 为空也返回 true?

转载 作者:行者123 更新时间:2023-11-30 21:29:15 40 4
gpt4 key购买 nike

这是我的代码:

    if(isset($_POST['make']) && isset($_POST['year']) && isset($_POST['mileage']))
{
$stmt = $pdo->prepare('INSERT INTO Autos (make,year,mileage) VALUES (:mk, :yr, :mi)');
$stmt->execute(array(':mk' => $_POST['make'],':yr' => $_POST['year'],':mi' => $_POST['mileage']));
$_POST = Array();
}

我收到一个错误:

Fatal error: Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column Automobiles.Autos.year at row 1 in /opt/lampp/htdocs/Automobiles/autos.php:15 Stack trace: #0 /opt/lampp/htdocs/Automobiles/autos.php(15): PDOStatement->execute(Array) #1 {main} thrown in /opt/lampp/htdocs/Automobiles/autos.php on line 15

不明白if里面的代码为什么执行,如果没有设置,为什么isset返回true?

最佳答案

您应该在插入之前验证年份参数并使用empty 进行检查

    function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}

if(!empty($_POST['make']) && !empty($_POST['year']) && !empty($_POST['mileage']) && validateDate($_POST['year']))
{
$stmt = $pdo->prepare('INSERT INTO Autos (make,year,mileage) VALUES (:mk, :yr, :mi)');
$stmt->execute(array(':mk' => $_POST['make'],':yr' => $_POST['year'],':mi' => $_POST['mileage']));
$_POST = Array();
}

关于php - 为什么 isset($_POST {'variable' ]) 即使数组 $_POST 为空也返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57206983/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com