How can I optimize my PHP code for efficiently searching and retrieving rows based on a substring within a URL field in a MySQL database?

To optimize your PHP code for efficiently searching and retrieving rows based on a substring within a URL field in a MySQL database, you can use the SQL LIKE operator with a wildcard (%) to match the substring. This can help improve the performance of your search query by allowing MySQL to use indexes efficiently. Additionally, you can consider using prepared statements to prevent SQL injection attacks.

<?php
// Assuming $searchTerm contains the substring you want to search for in the URL field
$searchTerm = "example";

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

// Prepare a SQL query using a wildcard to match the substring in the URL field
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE url_field LIKE :searchTerm");
$stmt->execute(['searchTerm' => "%$searchTerm%"]);

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

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