Why the sample values are added on each page visit
Your PHP code is executed every time you visit the page. It generates the page (writes parts of it dynamically, just copies everything outside <?php … ?>
), and the page is the output of your script. Apache, or whatever server software you use, just gets an HTTP request, executes your script, takes its output and sends it to the client in an HTTP response.
If your INSERT
query is executed unconditionally (as it is), it is also executed every time you visit the page. That's why the values are added over and over again.
How to stop adding the sample values
You may want to check if the cars
table was created and execute the insert query only if it was:
# Creating the table with rows start
# CHANGED: Notice that IF NOT EXISTS is not used anymore!
# Fails if the table already exists, not touching its original contents.
$db_query = 'CREATE TABLE `cars` (' .
'`id` int(11) NOT NULL AUTO_INCREMENT,' .
'`make` varchar(50) NOT NULL,' .
'`model` varchar(50) NOT NULL,' .
'`year` varchar(4) NOT NULL,' .
'`color` varchar(50) NOT NULL,' .
'`engine` decimal(2,1) NOT NULL,' .
'PRIMARY KEY (`id`));';
$result = mysqli_query($conn, $db_query);
# Creating the table with rows end
# Putting information in each column start
$db_query = 'INSERT INTO `cars`' .
' (`id`, `make`, `model`, `year`, `color`, `engine`)' .
' VALUES' .
' (NULL, \'Citroen\', \'Saxo\', \'1997\', \'White\', 1.1),' .
' (NULL, \'Citroen\', \'C3\', \'2012\', \'Blue\', 1.4),' .
' (NULL, \'Volkswagen\', \'Golf\', \'2010\', \'Blue\', 1.8),' .
' (NULL, \'Ford\', \'Mondeo\', \'2009\', \'Black\', 1.6),' .
' (NULL, \'Renault\', \'Clio\', \'2010\', \'Silver\', 1.2);';
# CHANGED: Executing the query only if previous query (`CREATE TABLE …`) succeeded.
if ($result) {
$result = mysqli_query($conn, $db_query);
}
# Putting information at each end
Refresh after a POST problem
Another problem we met during debugging the issue is refresh after POST form submission. Browser automatically submits the original form contents again, which is standard behavior. It results in inserting the submitted values to the database again, now storing them in two or even more copies.
This can be prevented, though. See e.g. Stop browsers asking to resend form data on refresh. The accepted answer recommends the POST-redirect-GET pattern, which is what I would use in your case. You can get much more on that topic when googling post data resent stackoverflow
.