Insert data into multiple tables using one form

Insert data into multiple tables using one form

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

Stefan Bogdanescu

Founder & Senior Architect

Inserting Data into Multiple Tables from a Single Form

When you submit a single HTML form to populate multiple database tables, the most common failure point isn't the HTML structure or the user interface logic. It's how the backend handles the transaction lifecycle and variable scoping. In the code you provided, the issue preventing data from landing in the donator table is not that one query works while the other fails; it is a classic case of variable shadowing combined with deprecated database functions.

The Variable Shadowing Trap

Look closely at your PHP logic:

$sql="INSERT INTO donator (nume, prenume, numar_telefon) VALUES ('$_POST[nume]','$_POST[prenume]','$_POST[numar]')";
$sql="INSERT INTO donatie (suma, data_donatie, IBAN) VALUES ('$_POST[suma]','$_POST[data]','$_POST[iban]')";
mysql_query($sql,$con);

You are reusing the same variable name $sql for two completely different SQL statements. When you execute mysql_query($sql, $con) the second time, it overwrites the content of $sql. By the time the function runs, $sql only contains the definition for the donatie table. The query intended for the donator table is lost in memory before it can ever reach the database server.

To fix this immediately, you must use distinct variable names for each statement, such as $sqlDonator and $sqlDonatie. This ensures both queries are executed sequentially without one overwriting the other.

The Legacy API Danger Zone

Beyond the immediate logic error, your code relies on the mysql_* extension functions (mysql_connect, mysql_select_db, mysql_query). These functions were deprecated in PHP 5.5 and completely removed in PHP 7.0. If you are running a modern version of PHP, your script will throw a fatal error and stop executing entirely before it can attempt any database operations.

The standard for writing secure, maintainable code today is to use PDO or the MySQLi extension with prepared statements. Prepared statements prevent SQL injection attacks by separating the SQL logic from the user data, whereas direct concatenation of $_POST variables into a string—as seen in your example—is highly vulnerable to malicious input.

Implementing a Robust Solution with PDO

Here is how you should refactor this logic using PDO. This approach handles multiple inserts cleanly and ensures that if one table fails to receive data, the other does not commit either (transactional integrity).

<?php
if(isset($_POST['submit'])) {
    // Define DSN, username, and password
    $host = 'localhost';
    $dbname = 'laborator';
    $user = 'root';
    $pass = '';

    try {
        // Create a PDO connection
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
        // Enable error reporting to see raw SQL errors
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Start a transaction to ensure atomicity
        $pdo->beginTransaction();

        // Prepare and execute the first insert for 'donator'
        $stmtDonator = $pdo->prepare("INSERT INTO donator (nume, prenume, numar_telefon) VALUES (:nume, :prenume, :numar)");
        
        if ($stmtDonator->execute([
            ':nume' => $_POST['nume'],
            ':prenume' => $_POST['prenume'],
            ':numar' => $_POST['numar']
        ])) {
            // Prepare and execute the second insert for 'donatie'
            $stmtDonatie = $pdo->prepare("INSERT INTO donatie (suma, data_donatie, IBAN) VALUES (:suma, :data, :iban)");

            if ($stmtDonatie->execute([
                ':suma' => $_POST['suma'],
                ':data' => $_POST['data'],
                ':iban' => $_POST['iban']
            ])) {
                // Only commit if both succeed
                $pdo->commit();
            } else {
                throw new PDOException("Failed to insert into donatie table.");
            }
        } else {
            throw new PDOException("Failed to insert into donator table.");
        }

    } catch (PDOException $e) {
        // Rollback on any error
        $pdo->rollBack();
        die("Database error: " . $e->getMessage());
    }
}
?>

Handling the Alert Message

Finally, address the frontend feedback. In your form, you have an onclick attribute attached to the submit button that triggers a JavaScript alert immediately upon clicking, regardless of whether the server actually processed the request successfully. This creates a false sense of completion. The user clicks "Donează," sees the success message, but then the page refreshes or errors out, causing confusion.

The alert should be removed from the HTML event handler. Instead, you should return to the user via an HTTP response after processing. If the insertion is successful, redirect the user back to a confirmation page or display a flash message at the top of the layout. This ensures the "success" state aligns with the actual database state, not just the click event.

By separating your SQL logic into distinct variables, migrating away from the removed mysql_* functions, and using transactions to maintain data consistency, you will ensure that both tables are populated correctly every time the form is submitted.

Our network