Sua Morales Sua Morales - 3 months ago 9
PHP Question

How do I submit form data to a database and redirect someone to URL?

PHP Newbie here: Quick question on forms and php,

Form in Html page

<form class="form" id="form" onsubmit="return validateForm()" method="post" action="submitdatabase.php">


I can insert data into my database successfully but how do I direct them to a certain URL as well?

If it helps, below is my PHP, needless to say it doesn't work:

<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES ('$_POST[fname]','$_POST[lname]','$_POST[address]','$_POST[phone]','$_POST[email]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}

mysql_close($con)
header("Location: URLREDIRECTION.com")
?>

Answer

PHP Newbie.. this should work
always use this to escape strings mysql_escape_string($var);
also mysql_connect() is depreciated, use mysqli_connect('host', 'user', 'password', 'database') instead.


<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}

$fname = mysql_escape_string($_POST['fname']);
$lname = mysql_escape_string($_POST['lname']);
$address = mysql_escape_string($_POST['address']);
$phone = mysql_escape_string($_POST['phone']);
$email = mysql_escape_string($_POST['email']);

mysql_select_db("database", $con);
$sql="INSERT INTO leads (fname, lname, address, phone, email)
VALUES 
('$fname','$lname','$address','$phone','$email')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
header("Location: http://yoursite.com");
Comments