Home >Backend Development >PHP Tutorial >How Can I Safely Include PHP Variables in MySQL INSERT Statements?
Inserting values into the contents table with a PHP variable as part of the VALUES clause can be problematic. Let's address the issue and provide the correct approach.
Ensuring correct handling of PHP variables in MySQL statements is crucial. The primary rule is to use prepared statements. Replace PHP variables with placeholders in your SQL statement and follow these steps:
Using MySQLi:
<?php $type = 'testing'; $reporter = "John"; $description = "whatever"; $sql = "INSERT INTO contents (type, reporter, description) VALUES ('$type', ?, ?)"; $mysqli->execute_query($sql, [$reporter, $description]); ?>
Using PDO:
<?php $type = 'testing'; $reporter = "John"; $description = "whatever"; $sql = "INSERT INTO contents (type, reporter, description) VALUES ('$type', ?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute([$reporter, $description]); ?>
For query parts like keywords or identifiers (database, table, or field names), use white list filtering. This involves explicitly comparing the PHP variable to a pre-defined list of allowed values. If the variable matches an allowed value, it's safe to include in the query. Otherwise, throw an exception for invalid input.
Following these guidelines ensures the secure and efficient handling of PHP variables in MySQL statements. Using prepared statements for variables representing data literals and white list filtering for identifiers guarantees data integrity and protection against injection attacks.
The above is the detailed content of How Can I Safely Include PHP Variables in MySQL INSERT Statements?. For more information, please follow other related articles on the PHP Chinese website!