Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into multiple tables using one form

Tags:

php

mysql

I am trying to insert data in 2 tables using one form.

This is my form

<form action="don.php" method="post">
<tr><td>
    <p>
        <label for="nume">Nume:</label></td>
        <td><input type="text" name="nume" id="nume" autocomplete="off"></td>
    </p>
    </tr>
    <tr><td>
    <p>
        <label for="prenume">Prenume:</label></td>
       <td> <input type="text" name="prenume" id="prenume" autocomplete="off"></td>
    </p></tr>
    <tr><td>
    <p>
        <label for="grupa">Numar telefon:</label></td>
        <td><input type="text" name="numar" id="numar" autocomplete="off"></td>
    </p></tr>
    <tr><td>
    <p>
        <label for="grupa">Suma:</label></td>
        <td><input type="text" name="suma" id="suma" autocomplete="off"></td>
    </p></tr>
    <tr><td>
    <p>
        <label for="grupa">Data:</label></td>
        <td><input type="text" name="data" id="data" autocomplete="off"></td>
    </p></tr>
    <tr><td>
    <p>
        <label for="grupa">IBAN:</label></td>
        <td><input type="text" name="iban" id="iban" autocomplete="off"></td>
    </p></tr>
    <tr><td><input type="submit" name="submit" value="Donează" onclick="alert('Operatiune finalizata cu succes. Va multumim!')"></td>
</form>

And this is my PHP code

<?php
if(isset($_POST['submit'])){
    $con=mysql_connect("localhost","root","");
    if(!$con)
    {
        die("Nu se poate face conexiunea la baza de date" . mysql_error());
    }

    mysql_select_db("laborator",$con);
    $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);
    mysql_close($con);
}
?>

When I press the submit button it shows me the alert that my dates were inserted, but only the second INSERT works. Table donator is empty. What should I do to fix this problem?

like image 732
Eleanordum Avatar asked Dec 04 '22 03:12

Eleanordum


1 Answers

You must call mysql_query() for every query.

$sql1 = "INSERT INTO donator ...";
$sql2 = "INSERT INTO donatie ...";
mysql_query($sql1, $con);
mysql_query($sql2, $con);

Important

mysql_query() is deprecated! Please use mysqli_query() http://php.net/manual/de/book.mysqli.php

You can also use mysqli_multi_query() http://php.net/manual/de/mysqli.multi-query.php

$query = "INSERT INTO donator ...; INSERT INTO donatie ...;";
mysqli_multi_query($link, $query);
like image 186
Scoutman Avatar answered Dec 06 '22 16:12

Scoutman