I'm very new to PHP and am trying out some examples. For some reason, when I click submit on the form, the data does not insert into my SQL database. Is there any reason it would not?
<!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;
?>
You should always check the return status from a database connection or preparing or executing the statement. That way you can get more information why it failed. You're catching the possible exception from the connection, which is good. But I notice that if a connection error does occur, your code just prints the error message, and then goes on as if the connection succeeded. In other words, you'll attempt to prepare an INSERT, even though you have no valid connection. You should stop the execution and don't do anything further with the db connection if it fails.
For example, instead of echo
, use die()
. This stops the script as it prints the error. As you get more adept with PHP, you can add HTML around the error, so it looks better and also gives the user links to go to another page to try again.
try {
$con = new PDO("mysql:host=$server;dbname=$db",$user,$pass);
}
catch(PDOException $e) {
die($e->getMessage());
}
Also an SQL statement can fail to prepare if you have no privileges on the table or if the table doesn't exist or you form the SQL syntax wrong, or any of some other reasons. An SQL statement can also fail on execute if you give values that are illegal, or an insert can fail if the disk is full, or other reasons.
In general, the return values are false
if there was a problem. Here's an example of checking them:
$q = "INSERT INTO names(fname,lname) VALUES(:firstname,:lastname)";
$query = $con->prepare($q);
if ($query === false) {
die(print_r($query->errorInfo()), true));
}
$result = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname
));
}
if ($result === false) {
die(print_r($query->errorInfo()), true));
}
If you get any errors, look them up in the mysql manual: http://dev.mysql.com/doc/refman/5.5/en/error-handling.html