0

I have this php file that allows a user to enter their favorite music artist. My program puts the entered artist in a variable called "art" and then adds it to an array called "artist". Then it displays the array in a bullet list. But the program as it is only allows one value to be in the array. When the user enters another artist, it overwrites the one that is already in the array. For example, the user writes "bob" as their favorite artist and presses submit. The program displays bob, but when you go to put in another artist, "tess", bob is gone and only tess is diplayed. How do i fix this?

Here is the code: (Don't mind the commented out echo, it was a test to see if the entered value was being assigned to the variable.)

<h1> My Favorite Artist </h1>
        
            <form method='POST'>
                <h3>Please enter your favorite artist</h3>
                <input type="text" name="artist">
                <input type="submit" value="Submit Artist">
    
            </form>
    <?php
    $art = $_POST['artist'];
    //echo "<h3> This $art </h3>";
    $artist = array();
    array_push($artist, $art);
    

    foreach ($artist as $a)
    {
        echo "<li>$a</li>";
    }




?>
2
  • 3
    You need to process the value of $_POST['artist'] into an array. Try splitting the values by a common delimiter (comma for example) using the 'explode' function (php.net/manual/en/function.explode.php). 'explode' function will give you an array of values which you can then load into the $artist array. Commented Nov 18, 2021 at 1:09
  • 2
    Sounds like you want to persist the $artist array between requests. Using session storage seems a good fit Commented Nov 18, 2021 at 1:11

1 Answer 1

1

You can try by creating a session of array and then print it like this.

<?php

    session_start();

?>
<h1> My Favorite Artist </h1>
        
            <form method='POST'>
                <h3>Please enter your favorite artist</h3>
                <input type="text" name="artist">
                <input type="submit" value="Submit Artist">
    
            </form>
    <?php
    if(isset($_POST['artist']))
    {
        
    $art = $_POST['artist'];
    //echo "<h3> This $art </h3>";
    if(empty($_SESSION['artist']))
    {
        $_SESSION['artist'] = array();
    }
    array_push($_SESSION['artist'], $art);
    
    
    $arry=$_SESSION['artist'];
    if(!empty($arry))
    {
        foreach ($arry as $a)
        {
            echo "<li>$a</li>";
        }
    }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.