Skip to content

Instantly share code, notes, and snippets.

@ggdx
Last active March 6, 2019 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggdx/85842904060ed12f2bbbae0d33f37c54 to your computer and use it in GitHub Desktop.
Save ggdx/85842904060ed12f2bbbae0d33f37c54 to your computer and use it in GitHub Desktop.
Basic contact form with DB
<?php
$errors = [];
$success = false;
if ($_POST) {
// Set required fields
$requires = ['email', 'name', 'message'];
foreach($requires as $field) {
if (!isset($_POST[$field])) {
$errors[] = $field;
}
}
// No errors: process form data
if (!count($errors)) {
// Set DB config
$db_host = '127.0.0.1';
$db_db = 'some_app';
$db_user = 'db_user';
$db_pass = 'db_pass';
$db_chars = 'utf8mb4';
$db_address = "mysql:host=$host;dbname=$db_db;charset=$db_chars";
$db_opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// Prepare and insert
$db = new PDO($db_address, $db_user, $db_pass, $db_opt);
$query = $db->prepare('INSERT INTO contact email, name, message VALUES (?, ?, ?)');
$query->execute([
$_POST['email'],
$_POST['name'],
$_POST['message'],
]);
$success = 'Thank you, your message has been sent';
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
} // if count errors
} // if $_POST
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Contact form demo</title>
</head>
<body>
<?php if(count($errors)) { ?>
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li class="error-message">Missing <?= $error; ?> field.</li>
<?php } // endforeach ?>
</ul>
<?php } //endif ?>
<?php if($success !== false) { ?>
<div class="success">
<?= $success; ?>
</div>
<?php } //endif ?>
<form action="<?= $_SERVER['REQUEST_URI']; ?>" method="post">
<div class="field">
<label for="name">Your name*</label>
<input type="text" name="name">
</div>
<div class="field">
<label for="email">Your email address*</label>
<input type="text" name="email">
</div>
<div class="field">
<label for="message">Message*</label>
<textarea name="message"></textarea>
</div>
<button type="submit">Send</button>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment