What are best practices for securely handling numerical values in PHP forms to prevent SQL injection vulnerabilities?
To securely handle numerical values in PHP forms to prevent SQL injection vulnerabilities, it is essential to sanitize user input by using prepared statements with parameterized queries. This approach ensures that input values are treated as data rather than executable SQL code, thereby preventing malicious injection attacks.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
// Set the parameter value and execute the statement
$id = $_POST['id'];
$stmt->execute();
// Process the result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the retrieved data
}
// Close the statement and connection
$stmt->close();
$conn->close();