我对 PHP 很陌生,正在尝试一些示例。出于某种原因,当我单击表单上的提交时,数据不会插入到我的 SQL 数据库中。有什么理由不这样做吗?
<!DOCTYPE HTML>
<?php
$server = 'x';
$user = 'x';
$pass = 'x';
$db = 'x';
try {
$con = new PDO("mysql:host=$server;dbname=$db",$user,$pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
<html>
<form name="Contact form" input type="text" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
First name: <input type="text" id="firstname" name="firstname"><br />
Last name: <input type="text" id="lastname" name="lastname"><br />
<input type="submit" id="submit" value="Submit this!" name="submit">
</form>
</html>
<?php
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$q = "INSERT INTO names(fname,lname) VALUES(:firstname,:lastname)";
$query = $con->prepare($q);
$result = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname
));
}
$con = null;
?>