How can PHP developers dynamically construct SQL queries based on user input to search for data in a database table?

To dynamically construct SQL queries based on user input in PHP, developers can use prepared statements with placeholders for user input values to prevent SQL injection attacks. By dynamically building the query based on the user's input, developers can create flexible search functionality in their applications.

// Example of dynamically constructing an SQL query based on user input to search for data in a database table

// Assuming $searchTerm is the user input for the search term
$searchTerm = $_POST['search'];

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

// Prepare the SQL query with a placeholder for the search term
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column_name LIKE :searchTerm");

// Bind the value of $searchTerm to the placeholder
$stmt->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);

// Execute the query
$stmt->execute();

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

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