Insert user input from textbox to Database (PHP to PHPMYADMIN using mysql)

Insert user input from textbox to Database (PHP to PHPMYADMIN using mysql)

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

Stefan Bogdanescu

Founder & Senior Architect

Why Your "Failed to Insert" Error Happens and How to Fix It

You are encountering a classic SQL injection vulnerability paired with a syntax error that prevents your application from executing any write operations. The specific error message "failed to insert" is a direct consequence of how you are constructing the query string using raw user input.

In your current implementation, you are retrieving values directly from $_POST and concatenating them into an SQL statement:

$query = ("INSERT INTO customer ([LName], [FName]...) VALUES ('$Lastname', '$firstname'...)");

This approach fails for two distinct reasons. First, the syntax is invalid. You are using square brackets [LName] inside the column list but parentheses () around the entire statement in a way that suggests a mix-up between MySQL and SQL Server conventions. In standard MySQL, column names must be enclosed in backticks (`) or left bare if they match exactly. Square brackets are reserved for SQL Server or T-SQL and will cause a syntax error in MySQL.

Second, and more critically, you are not escaping single quotes within the user input. If a user enters O'Connor into the "Last Name" field, your resulting query becomes:

INSERT INTO customer (LName...) VALUES ('O'Connor', ...)

MySQL interprets the quote after "O" as the end of the string value and then encounters an unexpected character, throwing a syntax error. This is why mysql_query($query) returns false. Beyond causing immediate failures, this pattern allows attackers to execute arbitrary code on your server by crafting inputs that alter the query logic entirely.

The Modern Solution: Prepared Statements

To resolve the "failed to insert" issue and secure your application, you must stop concatenating strings into SQL queries. Instead, use prepared statements. This technique separates the SQL logic from the data, ensuring that user input is always treated strictly as text, regardless of what characters it contains.

Your code relies on the deprecated mysql_* extension, which has been removed from PHP 7.0+. You should migrate immediately to mysqli or PDO. Here is how you would refactor the logic using mysqli prepared statements:

if (isset($_POST['submit'])) {
    $conn = new mysqli($dbhost, $dbuser, $dbpass, $db);

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

    // Set character set to handle UTF-8 correctly
    $conn->set_charset("utf8mb4");

    $firstname = trim($_POST['FirstName']);
    $lastname  = trim($_POST['LastName']);
    $middlename = trim($_POST['MiddleName']);
    $address = trim($_POST['Address']);
    $city = trim($_POST['City']);
    $zipcode = trim($_POST['ZipCode']);
    $email = trim($_POST['email']);
    $number = trim($_POST['number']);

    // Define the SQL statement with placeholders
    $stmt = $conn->prepare("INSERT INTO customer (LName, FName, MName, Street, City, ZipCode, Email, ContactNo) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

    // Bind parameters. 's' stands for string.
    $stmt->bind_param("ssssssss", $lastname, $firstname, $middlename, $address, $city, $zipcode, $email, $number);

    if ($stmt->execute()) {
        echo "<script>alert('INSERTED SUCCESSFULLY');</script>";
    } else {
        // Helpful for debugging: show the actual error message
        echo "<script>alert('FAILED TO INSERT: " . $stmt->error . "');</script>";
    }

    $stmt->close();
}
?>

Key Implementation Details and Trade-offs

  1. Column Naming: Switch from square brackets to standard MySQL syntax. Use backticks only if column names contain spaces or special characters (e.g., customer table with column `L Name`). Otherwise, simple identifiers like LName are preferred for readability.
  2. Parameter Binding: The bind_param method ensures that the data types match the placeholders. This prevents type coercion errors that often lead to silent failures or unexpected behavior.
  3. Input Sanitization vs. Escaping: While mysqli_real_escape_string() was a common pattern in legacy code, prepared statements are superior because they handle escaping automatically at the driver level without requiring manual function calls for every variable.
  4. Error Handling: Relying solely on an alert box to say "failed" is insufficient for debugging. Always log the specific error returned by $stmt->error or mysql_error() during development to pinpoint syntax issues quickly.

Moving Forward with Frameworks

If you are maintaining legacy PHP code, fixing these issues manually is a valid path. However, if you are starting a new project or looking to refactor significantly, consider adopting a modern framework like Laravel. Laravel provides robust built-in support for database interactions using Eloquent ORM and PDO, which enforces prepared statements by default.

For developers interested in leveraging modern PHP practices, resources at https://laravelcompany.com offer detailed guides on securing applications and adopting best practices that move you away from raw SQL strings entirely. Transitioning to these patterns not only fixes the immediate "insert failed" error but also future-proofs your application against evolving security threats.

Our network