My notes on how to create a LAMP form using PDO and MySQL:
Part 4: Retrieve all records
This is part 4 of a series:
Part 1 - Prepare mysql
Part 2 - Create the mysql login files
Part 3 - Retrieve all records
Part 4 - Insert a new record
Part 5 - Search for a record
Part 6 - Embed the form
Create a PHP form to insert a new record:
Contents of form1.php:
<?php // form1.php
echo <<<_END
<html>
<head>
<title>Form1 Test</title>
</head>
<body>
<form method="post" action="form1.php">
Values must be entered for BOTH fields.<br><br>
First name: <input type="text" name="firstName"> <br><br>
Last name: <input type="text" name="lastName"> <br>
<br>
<input type="submit" value="submit">
</form>
<hr>
<br>
_END;
// Set variable $lastName if it was provided via a POST method
if (isset($_POST['lastName']) && (!empty($_POST['lastName'])))
{
// This is the code that sanitizes the user's input string
//$lastName = filter_var($_POST['lastName'], FILTER_SANITIZE_STRING);
$lastName = filter_var($_POST['lastName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STR
IP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK | FILTER_FLAG_ENCODE_AMP );
}
// Set variable $firstName if it was provided via a POST method
if (isset($_POST['firstName']) && (!empty($_POST['firstName'])))
{
// Sanitize the user's input string
$firstName = filter_var($_POST['firstName'], FILTER_SANITIZE_STRING, FILTER_FLAG_S
TRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK | FILTER_FLAG_ENCODE_AMP );
}
if (!empty($lastName) && !empty($firstName) )
{
echo "Entered First Name: $firstName<br>";
echo "Entered Last Name: $lastName<br>";
echo '<br>';
// Insert the values into the mysql database
// To Do:
// - Check for existing entry. Reject attempt if match exists.
// Retrieve database connection info
require_once '/var/forms/login_writer.php';
// Build data source name and options
$dsn = "mysql:dbname=$db;host=$host;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE=> PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
// Build a PDO object
$pdo = new PDO($dsn, $user, $pass, $opt);
// Prepare the SQL statement to protect against SQL injection attacks.
$statement = $pdo-> prepare( "
INSERT INTO Form1
VALUES (DEFAULT, ?, ?)
" );
// Now that the SQL statement is prepared, execute it
// Provide the parameters
$statement->execute([$lastName, $firstName]);
echo "Added...";
}
// Deal with problems with the database
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
echo '<br>';
echo '<br>';
echo '<br>';
echo'Click <a href="index.html">here</a> to return to Main Menu';
echo '<br>';
echo '</html>';
?>