I’m adding a contact to my database with a form on the page add.php, the INSERT code for this form is on another page we’ll call php.php page. In php.php I have a header function which I would like to have redirect the user to another page edit.php?ID=100, ID=100 being the contact that was just entered. How would I do this, do I need to do a fetch from the db before the header function and INSERT query?
<?php
if (isset($_POST['$fname'])) {
header("location: http://www.mydomain.com/contacts/edit/?ID=<? echo $row['ID]; ?>");
$connect = mysql_connect (...)
mysql_select_db ("mydb);
$ID = $_POST['ID'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sql = ("INSERT INTO contacts (fname, lname) VALUES ('$_POST[fname]', '$_POST[lname]')");
mysql_query($sql,$con) or die ("Error: ".mysql_error());
exit;
}
?>
I believe mysql_insert_id is the function you’re looking for. It’ll return the AUTO_INCREMENT ID of the field that was just inserted. You can then plug that into your header redirect. Just make sure to do the header redirect AFTER you insert the contact. It’ll work just fine.
Code that should work:
The code you posted was also susceptible to MySQL injections, so I mysql_real_escape_string’d your input to prevent that from happening. Always sanitize input before putting it into your query. I encourage you to look at the MySQLi functions that PHP has to offer.