PHP运行脚本后用空值重新加载



我是PHP的新手,最近我尝试创建一个;系统";将客户添加到SQLite数据库并在表中显示。好吧,每次我导航到HTML页面以添加新客户时,脚本都会自己运行,在数据库中创建空值。当我在填写完值后单击提交时,它会正常工作。下面我附上我的代码,用于";系统";。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Customer</title>
<style>
form {
display:flex;
flex-direction:column;
width:65%;
max-width:75%;
margin:0 auto;
}
</style>
</head>
<body>
<form action="" method="POST">
<h1>Insert a new customer</h1>
<label for="id">Customer Id</label>
<input type="text" name="id" id="id">
<label for="name">Customer Name</label>
<input type="text" name="name" id="name">
<label for="age">Customer Age</label>
<input type="number" name="age" id="age">
<label for="address">Customer Address</label>
<input type="text" name="address" id="address">
<button type="submit">Submit</button>
</form>
<?php 

class COMPANY extends SQLite3 {
function __construct() {
$this->open('customers.db');
}
}

$database = new COMPANY();
if (!$database) {
echo $database->lastErrorMsg();
} else {
echo "Database accessed!n";
}

$insert ="INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS) VALUES ('".$_POST["id"]."', '".$_POST["name"]."', '".$_POST["age"]."','".$_POST["address"]."');";

$result = $database->exec($insert);
if(!$result) {
echo $database->lastErrorMsg();
} else {
echo "Records added successfully!n";
}
$database->close();
?>

</body>
</html>

您需要使用isset()并检查表单是否实际发布了值。在您的代码中,页面加载并执行PHP代码,而不检查表单是否已提交,空白是否已插入数据库

if(isset($_POST['id'],isset($_POST['name'],isset($_POST['age'], isset($_POST['address']) {
.. your code
}

PS:这不包括字段的消毒和验证,请根据您的意愿添加

应该有验证,值不应该为空。

最新更新