Sanitizing Variables prevents users from being able to submit data to a database such as HTML formatting or JavaScript code.
filter_var works based off of specific filters that you designate that can be found at: https://www.php.net/manual/en/filter.filters.sanitize.php
Form.html
<html>
<body>
<form action="phpForm.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
Gender: <select name="gender">
<option value=" "> </option>
<option value="boy">Boy</option>
<option value="girl">Girl</option>
</select><br>
<input type ="submit">
</form>
</body>
</html>
phpForm.php – With filter_var Sanitization
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$name = filter_var($name,FILTER_SANITIZE_STRING);
$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into students(name,age,gender) values('$name','$age','$gender')";
if ($conn->query($sql) === TRUE) {
echo "ADDED: ".$name.", ".$age.", ".$gender;
} else {
echo "Error: ".$sql."<br>".$conn->error;
}
$conn->close();
?>
filteredSelect.php – Print a report of records
<?php
$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";
$conn = new mysqli($servername, $username, $password, $db);
if($conn->connect_error){
die("Connection failed ".$conn->connect_error);
}
$sql = "select * from students";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
echo $row["student_id"] ." " .$row["name"]." ".$age["age"]." ".$row["gender"]. "<br>";
}
} else {
echo "0 records";
}
$conn->close();
?>
Be the first to comment