What security measures should be implemented to prevent SQL injection when using user input in PHP queries?
To prevent SQL injection when using user input in PHP queries, you should use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input, preventing malicious SQL code from being executed.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// User input
$userInput = $_POST['userInput'];
// Prepare a SQL query using a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput);
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();
Related Questions
- How can PHP developers handle the integration of external packages with specific commits in a way that ensures maintainability and stability?
- What is the significance of using "&" or "&" in the query string in PHP?
- What are the best practices for extracting specific values from a URL string in PHP, considering different scenarios like positive and negative numbers?