I'm super new to PHP and I recently tried to create a "system" that adds customers to the SQLite database and displays them in a table. Well, every time I navigate to the HTML page in order to add a new customer, the script runs itself creating empty values within the database. When I click submit after filling the values it just works properly. Below I attach my code for this specific part of the "system".
<!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>
CodePudding user response:
You need to use isset()
and check if the form has actually posted the values. In your code, the page loads and PHP code executes without checking if the form has submitted and the blanks are inserted in the database
if(isset($_POST['id'],isset($_POST['name'],isset($_POST['age'], isset($_POST['address']) {
.. your code
}
PS: this doesn't include sanitization and validation of fields, please add them as you wish
CodePudding user response:
There should be validation, values should not be empty.