What is the recommended method to link a MySQL table to a radio button for image switching in PHP?

To link a MySQL table to a radio button for image switching in PHP, you can first retrieve the image URLs from the database and store them in an array. Then, you can use JavaScript to switch the image source based on the radio button selection.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve image URLs from MySQL table
$sql = "SELECT image_url FROM images";
$result = $conn->query($sql);

$images = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $images[] = $row["image_url"];
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Image Switching</title>
</head>
<body>
    <form>
        <?php foreach($images as $image): ?>
            <input type="radio" name="image" value="<?php echo $image; ?>"><?php echo $image; ?><br>
        <?php endforeach; ?>
    </form>

    <img id="image" src="<?php echo $images[0]; ?>">

    <script>
        document.querySelectorAll('input[name="image"]').forEach(item => {
            item.addEventListener('change', event => {
                document.getElementById('image').src = event.target.value;
            });
        });
    </script>
</body>
</html>