If you're looking for guidance on saving form variables to a MySQL database, I'll provide a brief example along with some keywords to help you get started.
Below is the basic HTML markup of a form with fields styled using bootstrap classes:
<form action="process_form.php" method="POST" class="form">
<div class="form-group">
<input type="text" name="firstname" placeholder="First name" class="form-control" />
<input type="text" name="lastname" placeholder="Last name" class="form-control" />
<textarea name="message" placeholder="Message" class="form-control"></textarea>
<input type="submit" value="Submit" class="btn btn-primary btn-lg pull-right" />
</div>
</form>
This form includes two important attributes: action and method.
The action attribute specifies the script that will process the form data upon submission, while the method attribute defines how the form data should be sent.
Let's examine the content of the process_form.php file:
$servername = "localhost";
$username = "username";
$password = "password";
if (!empty($_POST)) {
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['message']) ) {
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$message = $_POST['message'];
$sql = "INSERT INTO messages (firstname,lastname,message) VALUES (:firstname,:lastname,:message)";
$q = $conn->prepare($sql);
$q->execute(array( ':firstname' => $firstname,
':lastname' => $lastname,
':message' => $message));
echo "Successfully inserted";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
}
The code checks for POST requests and validates the expected form variables before attempting to establish a connection to a MySQL database using PHP Data Objects (PDO). If successful, it prepares and executes the SQL statement for inserting data. Any errors are caught and displayed for debugging purposes. There's also an alternative approach discussed for storing JSON data in the database.
// Sample code for creating a JSON string from form variables
$jsonObj = new stdClass();
$jsonObj->firstname = $_POST['firstname'];
$jsonObj->lastname = $_POST['lastname'];
$jsonObj->message = $_POST['message'];
$json = json_encode($jsonObj);