How can SQL injection vulnerabilities be mitigated in the dynamic query construction process within a PHP script for database searches?

SQL injection vulnerabilities can be mitigated in the dynamic query construction process within a PHP script by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.

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

// User input from a form
$searchTerm = $_POST['search'];

// Prepare a SQL query using a parameterized query
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE column_name = :searchTerm');
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll();

// Display results
foreach ($results as $row) {
    echo $row['column_name'] . "<br>";
}