How can PHP developers prevent SQL injection when storing SQL commands in a table for logging purposes?

To prevent SQL injection when storing SQL commands in a table for logging purposes, PHP developers should use prepared statements with parameterized queries. This method ensures that user input is treated as data rather than executable code, thus preventing malicious SQL injection attacks.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO log_table (sql_command) VALUES (:sql_command)");

// Bind the SQL command as a parameter
$stmt->bindParam(':sql_command', $sql_command);

// Set the SQL command variable and execute the statement
$sql_command = "SELECT * FROM users";
$stmt->execute();