I made a small script to update fields in a database. I'm using PDO to connect to MySQL. All the business logic of PHP is in the top half of the file, and the form is at the bottom.
Here is the full code. If it's a POST request, it opens the PDO connection and inserts the values from the form.
<?php
/**
* Use an HTML form to update the users table
* with new entries.
*
*/
if ($_POST)
{
require_once "config.php";
require_once "common.php";
try
{
$connection = new PDO($dsn, $username, $password, $options);
$sql = "INSERT INTO users (firstname, lastname, email, age, location)
VALUES (:firstname, :lastname, :email, :age, :location)";
$statement = $connection->prepare($sql);
$statement->execute(array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"email" => $_POST['email'],
"age" => $_POST['age'],
"location" => $_POST['location']
));
}
catch(PDOException $error)
{
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/primitive.css">
<title>Update Users</title>
</head>
<body>
<div class="small-container">
<h1>Add a user</h1>
<form method="post">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname">
<label for="email">Email Address</label>
<input type="text" name="email" id="email">
<label for="age">Age</label>
<input type="text" name="age" id="age">
<label for="location">Location</label>
<input type="text" name="location" id="location">
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
I know I can sanitize HTML input by doing something like:
function escape($html)
{
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
// example use
escape($_POST['firstname']);
I'm wondering how necessary it is when I'm using a prepared statement. I'm still a bit confused about sanitization and filtering, and when it's necessary. I know it's necessary when printing data out to HTML, but not sure how much when receiving input to PDO.
Please forgive any and all ignorance. I'm writing this from scratch and doing my best to teach myself PHP without frameworks.