Connecting HTML Forms to MySQL: The Missing Link in Your Insert Query
You have a working SQL INSERT statement, and your database connection file is ready. The logic holds up in isolation, but as soon as you wrap it around a "Submit" button, the code stops running. This disconnect happens because PHP scripts are stateless; they only execute when explicitly called by the web server. A static HTML page containing a <form> element and a submit button does not automatically trigger the PHP code behind it unless that form is configured to send data back to a specific script.
The core issue in your current snippet lies in how the request lifecycle works. When you place the include('db_connect.php'); and the $SQL statement inside a standard HTML file, that code runs immediately upon loading the page. You are executing the database insert before the user even interacts with the form. To fix this, you must separate the data presentation from the data processing.
Structuring the Form and Handler
To execute an insert only when the button is clicked, you need two distinct files: a view file that renders the HTML form, and a controller or handler file that processes the submission.
In your HTML file, define the form's action attribute to point to the PHP script responsible for handling the logic. Set the method to POST, which is the standard convention for submitting data that alters server state.
<form action="insert_entry.php" method="POST">
<input type="text" name="name" value="4-6 Days" readonly>
<input type="text" name="price" value="75.00" readonly>
<!-- Optional: Allow dynamic ID or leave empty for auto-increment -->
<button type="submit">Submit</button>
</form>
In the insert_entry.php file, you will place your database logic. This script should first check if any data was actually posted via the $_POST superglobal array before attempting to interact with the database.
<?php
// Ensure POST data exists before proceeding
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
include('db_connect.php');
// Sanitize and validate input is critical for security
$name = isset($_POST['name']) ? $_POST['name'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : '';
if (!empty($name) && !empty($price)) {
// Use prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("INSERT INTO chosenitems (ID, Name, Price) VALUES (?, ?, ?)");
// Bind parameters: 's' for string, 'd' for double/float
$stmt->bind_param("sd", '', $name, $price);
if ($stmt->execute()) {
echo "Entry added successfully.";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
} else {
echo "Please provide valid data.";
}
}
?>
Addressing Critical Security and Architecture Issues
Your original code snippet uses the mysql_query() function. This extension was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0. Continuing to use it will cause fatal errors on modern servers and leaves your application vulnerable to SQL injection attacks. The solution is to migrate to either MySQLi or PDO.
Furthermore, your query attempts to insert a value for ID manually (VALUES ('', ...)). If the ID column in your chosenitems table is defined as an AUTO_INCREMENT primary key, you must not provide a value for it. Passing an empty string can lead to data integrity issues or unexpected behavior depending on the specific database configuration. Instead, allow the database to generate the unique identifier automatically by omitting that column from the INSERT statement or passing NULL.
Finally, executing raw SQL without checking for errors provides no feedback if something goes wrong. Always inspect the result of your query execution. In modern frameworks like Laravel, these patterns are abstracted away using Eloquent models and form request classes to handle validation automatically. While the direct PHP approach offers granular control for simple scripts, understanding how data flows from the client-side form to the server-side handler is fundamental to building secure applications. For those looking to scale beyond raw PHP files, exploring structured frameworks like Laravel can streamline these interactions significantly.