Cepheus
Cepheus

Reputation: 4903

Inserting multiple fields with a similar name

I have a form I'm using to send multiple fields with a similar name but using square brackets to send them as an array with the key being 'id'. I am able to loop through successfully using a foreach loop but my insert query fails to make any changes in the db.any clues as to why?

here is the code from the form:

$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];

while ($music = mysql_fetch_array($allmusic)) {
    echo "<td class=\"td20 tdblue\">
        <input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
        </td>"; 
}

and here is the code on my form processor

foreach ($_POST['song_title'] as $id => $song) {
    $query = "UPDATE music SET 
                song_title = '{$song}' 
                WHERE id = $id ";
    if (mysql_query($query, $connection)) {
        //Success
        header("Location: yourmusic.php?pid=3");
        exit;
    } else {
        //Display error message
        echo "update did not succeed";
        echo "<p>" . mysql_error() . "</p>";
    }
}

Upvotes: 0

Views: 77

Answers (1)

michalzuber
michalzuber

Reputation: 5215

Try this.

Also watch for security http://www.phptherightway.com/#data_filtering

foreach ($_POST['song_title'] as $id => $song) {
                    $id = (int) $id;
                    $song = mysql_real_escape_string($song);

                    $query = "UPDATE music SET 
                    song_title = '$song' 
                    WHERE id = $id LIMIT 1;";

                    if (mysql_query($query, $connection)) {
                    //Success
                    header("Location: yourmusic.php?pid=3");
                    exit;
                } else {
                    //Display error message
                    echo "update did not succeed";
                    echo "<p>" . mysql_error() . "</p>";
                }
            }

Upvotes: 1

Related Questions