What are the best practices for storing images obtained from external websites in a MySQL database in PHP?

When storing images obtained from external websites in a MySQL database in PHP, it is best practice to store the image URL in the database rather than the actual image itself. This reduces database size and improves performance. To display the image, you can simply retrieve the URL from the database and use it in an <img> tag in your HTML code.

// Assuming you have a table named &#039;images&#039; with columns &#039;id&#039; and &#039;image_url&#039;

// Connect to MySQL database
$servername = &quot;localhost&quot;;
$username = &quot;username&quot;;
$password = &quot;password&quot;;
$dbname = &quot;database&quot;;

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn-&gt;connect_error) {
    die(&quot;Connection failed: &quot; . $conn-&gt;connect_error);
}

// Insert image URL into database
$imageUrl = &quot;https://www.example.com/image.jpg&quot;;
$sql = &quot;INSERT INTO images (image_url) VALUES (&#039;$imageUrl&#039;)&quot;;

if ($conn-&gt;query($sql) === TRUE) {
    echo &quot;Image URL inserted successfully&quot;;
} else {
    echo &quot;Error: &quot; . $sql . &quot;&lt;br&gt;&quot; . $conn-&gt;error;
}

// Close database connection
$conn-&gt;close();