I am having trouble inserting data to my table via PHP. The "cc_connect.php" is the file that connects the database. The form is there but when I submit it, no data is added to my table. I've followed several tutorials and matched their methods without success. Is something not set up in my db?
the function $dbcon is associated with my connection
<form method="post" action="cc_registration.php">
<input type="hidden" name="submitted" value="true" />
First Name: <input type="text" name="first_name" />
Last Name: <input type="text" name="last_name" />
<br />
<input type="submit" value="submit" />
<?php
if(isset($_POST['submit'])) {
include ('cc_connect.php');
if (!$dbcon) {
die("Can not Connect: " . mysql_error());
}
mysql_select_db("cooperstown",$dbcon);
$sql = "INSERT INTO cobra_registration (first_name,last_name) VALUES ('$_POST[first_name]', '$_POST[last_name]')";
mysql_query($sql,$dbcon);
mysql_close($dbcon);
}
?>
$_POST['submit']
is never set because you are passing submitted
.
change:
<input type="hidden" name="submitted" value="true" />
to:
<input type="hidden" name="submit" value="true" />
As a side note your current query can easily be hacked. Use Prepared statements instead like PDO or MysQLi, here is an example in PDO:
$fName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lName = isset($_POST['last_name']) ? $_POST['last_name'] : '';
if ($fName && $lName) {
$stmt = $db->prepare('
INSERT INTO cobra_registration (first_name,last_name)
VALUES (:fname, :lname)
');
$stmt->bindParam(':fname', $fName, PDO::PARAM_STR);
$stmt->bindParam(':lname', $lName, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
echo 'Success';
} else {
echo 'Failure';
}
}
The mysql_* functions are deprecated, and should no longer be used. Look into mysqli or PDO .
IMPORTANT NOTE
This is WIDE open to SQL Injection attacks . You should use prepared statements to protect against such attacks.
GGio nailed his answer, it was the submitted
, but checking for submit
. He also provided a PDO example, so I'll demonstrate the same thing in mysqli:
$firstName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lastName = isset($_POST['last_name']) ? $_POST['last_name'] : '';
if ($firstName && $lastName) {
$stmt = $mysqli->prepare("INSERT INTO cobra_registration (first_name,last_name)
VALUES (?, ?)");
$stmt->bind_param("ss", $firstName, $lastName);
$stmt->execute();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.