Send html form data to sql database via php (using mysqli)

Send html form data to sql database via php (using mysqli)

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Silent Failure in Your INSERT Statement

You have a working database connection, your HTML form correctly populates the $_POST superglobal array, and you are attempting to insert that data into a table named posts. Yet, the query fails. The culprit is almost certainly not your server configuration or the MySQLi driver; it is how you are constructing the SQL string itself.

In the code snippet provided, the values are being concatenated directly into the SQL command:

mysqli_query($connect,"INSERT INTO posts (category, title, contents, tags)
VALUES ('$_POST[post_category]', '$_POST[post_title]', '$_POST[post_contents]', '$_POST[post_tags]')";
?>

This approach is known as string interpolation or direct concatenation. While it might seem intuitive to simply wrap the PHP variable in quotes and append it to the query, this method creates two critical vulnerabilities and functionality gaps: SQL injection and data truncation.

The Security Vulnerability

When you concatenate $_POST values directly into the query string, you open your database to SQL injection attacks. If a user enters <script>alert('XSS')</script> into the post_title field, that exact string becomes part of the executed SQL command. Instead of inserting a title with text in it, the database interprets the quotes as delimiters and executes arbitrary code.

Even if you think your inputs are sanitized, relying on input validation is a fragile defense. The robust approach is to use prepared statements. This separates the SQL logic from the data being inserted. The database parses the query structure first, then binds the user's data strictly as text or numbers, preventing any special characters (like quotes or semicolons) from altering the command's execution flow.

Handling Data Types and Truncation

Beyond security, there is a syntax error inherent in your current approach regarding data types. Your contents field likely holds HTML formatted by a <textarea>. By wrapping this raw input in single quotes ('$_POST[post_contents]'), you are forcing MySQL to treat it as a string literal. However, if the user's input contains a single quote (apostrophe) within the text—common when writing code or prose—the query breaks immediately because the quote closes the string prematurely.

Furthermore, your table schema includes an auto_increment primary key (pid). In your INSERT statement, you list specific columns: category, title, contents, and tags. You are correctly omitting pid from the column list, which allows MySQL to generate a new unique ID automatically. However, if you were to include pid in the column list without specifying a value, the database would throw an error regarding duplicate key values or missing primary keys, depending on the specific configuration.

The Correct Implementation

To resolve these issues, switch to using mysqli_prepare. This method ensures that user input is never treated as SQL code, but strictly as data. Here is how the corrected logic should look:

<?php
// Establish connection (ensure it's persistent or reuse a singleton)
$connect = mysqli_connect("my host", "my user", "my passwrod", "my db");

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}

// Prepare the statement with placeholders
$stmt = $connect->prepare("INSERT INTO posts (category, title, contents, tags) VALUES (?, ?, ?, ?)");

// Bind parameters. 's' stands for string.
// This ensures that even if the input contains quotes, the SQL structure remains intact.
$stmt->bind_param("ssss", 
    $_POST['post_category'], 
    $_POST['post_title'], 
    $_POST['post_contents'], 
    $_POST['post_tags']
);

// Execute the query
if ($stmt->execute()) {
    echo "New row created successfully.";
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
?>

Form Submission Mechanics

Finally, examine your HTML form. You have defined onSubmit="send_post.php" as an attribute on the <form> tag. This syntax is invalid in standard HTML5 and will likely be ignored by modern browsers, meaning the form submits to whatever URL is currently loaded or defaults to the same page.

To ensure the form data actually reaches your script, you must set the action attribute of the <form> element:

<form action="send_post.php" method="post">
    <!-- form fields -->
</form>

Additionally, remove the onSubmit handler unless you have specific JavaScript logic to intercept the submission before it happens. Relying on server-side processing for data integrity is best practice when dealing with database writes.

By moving to prepared statements and correcting your form's action attribute, you eliminate SQL injection risks, handle special characters safely, and ensure the data flows exactly as intended from the user's browser to your posts table.

Our network