Skip to content

Instantly share code, notes, and snippets.

@daveh
Last active July 11, 2024 16:30
Show Gist options
  • Save daveh/c5a691136c7e3b81dc8e72b3fc1054b3 to your computer and use it in GitHub Desktop.
Save daveh/c5a691136c7e3b81dc8e72b3fc1054b3 to your computer and use it in GitHub Desktop.
HTML to MySQL using PHP (code to accompany https://youtu.be/Y9yE98etanU)
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
<meta charset="UTF-8">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.min.css">
</head>
<body>
<h1>Contact</h1>
<form action="process-form.php" method="post">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
<label for="priority">Priority</label>
<select id="priority" name="priority">
<option value="1">Low</option>
<option value="2" selected>Medium</option>
<option value="3">High</option>
</select>
<fieldset>
<legend>Type</legend>
<label>
<input type="radio" name="type" value="1" checked>
Complaint
</label>
<br>
<label>
<input type="radio" name="type" value="2">
Suggestion
</label>
</fieldset>
<label>
<input type="checkbox" name="terms">
I agree to the terms and conditions
</label>
<br>
<button>Send</button>
</form>
</body>
</html>
<?php
$name = $_POST["name"];
$message = $_POST["message"];
$priority = filter_input(INPUT_POST, "priority", FILTER_VALIDATE_INT);
$type = filter_input(INPUT_POST, "type", FILTER_VALIDATE_INT);
$terms = filter_input(INPUT_POST, "terms", FILTER_VALIDATE_BOOL);
if ( ! $terms) {
die("Terms must be accepted");
}
$host = "localhost";
$dbname = "message_db";
$username = "root";
$password = "";
$conn = mysqli_connect(hostname: $host,
username: $username,
password: $password,
database: $dbname);
if (mysqli_connect_errno()) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "INSERT INTO message (name, body, priority, type)
VALUES (?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if ( ! mysqli_stmt_prepare($stmt, $sql)) {
die(mysqli_error($conn));
}
mysqli_stmt_bind_param($stmt, "ssii",
$name,
$message,
$priority,
$type);
mysqli_stmt_execute($stmt);
echo "Record saved.";
@daveh
Copy link
Author

daveh commented Jun 22, 2024

@zoro7sn It looks like you don't have a primary key in your table, which makes it difficult to uniquely identify individual rows. There's an article here that might help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment