So, I have one form and I'm trying to insert data (via POST) to two tables.
There is a foreign key linking both tables by AUTO_INCREMENT ID
.
I've searched the site extensively and tried all the suggested (for those issues) and none worked.
I'd assume this is because their problem was similar, but not exact to mine.
Here's my PHP:
// Escape user inputs for security
$companyName = mysqli_real_escape_string($con, $_REQUEST['companyName']);
$companyAddress =mysqli_real_escape_string($con,$_REQUEST['companyAddress']);
$companyCity = mysqli_real_escape_string($con, $_REQUEST['companyCity']);
$companyState = mysqli_real_escape_string($con, $_REQUEST['companyState']);
$companyZip = mysqli_real_escape_string($con, $_REQUEST['companyZip']);
$companyPhone = mysqli_real_escape_string($con, $_REQUEST['companyPhone']);
$companyURL = mysqli_real_escape_string($con, $_REQUEST['companyURL']);
$contactName = mysqli_real_escape_string($con, $_REQUEST['contactName']);
$contactEmail = mysqli_real_escape_string($con, $_REQUEST['contactEmail']);
$contactPosition = mysqli_real_escape_string($con,$_REQUEST['contactPosition']);
// Attempt insert query execution
$sql1 = "INSERT INTO companyData (companyName, companyAddress, companyCity, companyState, companyZip, companyPhone, companyURL)
VALUES ('$companyName', '$companyAddress', '$companyCity', '$companyState', '$companyZip', '$companyPhone', '$companyURL')";
$sql2 = "INSERT INTO contactData (contactName, contactEmail, contactPhone, contactPosition)
VALUES ('$contactName', '$contactEmail', '$contactPhone', '$contactPosition')";
if (!mysqli_query($con,$sql1))
{
die('Error: ' . mysqli_error($con));
}
if (!mysqli_query($con,$sql2))
{
die('Error: ' . mysqli_error($con));
}
echo "<center><h1>Record updated successfully.<br>
Go <a href='data/form_companyinfo.php'>Here </a>Next</h1></center>";
You haven't told us the error message or described exactly your database schema, but here's a guess:
Use mysqli_insert_id()
after the first insert so that you can supply the resulting id (returned by mysqli_insert_id()
) to the following INSERT statement.