My site searches the Spotify Library and returns a list of results. Users can click on one of the results and have it added to a playlist which will in turn be posted as part of a form submit. The code below adds the clicked song to a .selected-list container, then adds a hidden input to the DOM with the value of the Spotify song href.
$('.spotify-result').click(function() {
var $input = $('<input type="hidden" id="track_href" class="track" value="" name="track_href" />');
$(this).clone().appendTo($('.selected-list'));
$('.submit-spotify').before($input);
$input.val($('.track-href', this).text());
});
The issue that I have here is that each input is being given an id of 'track_href', and it is this which is sent in the $_POST variable. The PHP below shows how I am adding this to my table.
$song_query = "INSERT INTO songs (playlist_id, href) VALUES ('$playlist_id', '$href')";
if (mysql_query($song_query)) {
$message = "<p>Congratulations, your Journix has been added.</p>";
} else {
$message = ("Insert failed. " . mysql_error() . "<br/>" . $song_query);
}
What happens at the minute is only the first song is added to the table. I need some kind of loop I'm guessing to loop through each input, but I'm sure that posting each input with the same id isn't the way to go about it.
I'm aware that mysql functions are being depreciated but this is for a University project which requires me to use mysql.
There are two issues.
First, html ids must be unique. This doesn't really affect you unless you're using jquery to grab those ids, but you should still change it. Do you really even need an id?
Second, inputs with the same name will overwrite each other. To save it all, I'd make it an array.
name="track_href[]"
After that, you can just loop through $_POST['track_href'] and do the inserts.
It is the name, not id of an input, that is a key in $_POST array.
it isnt the id
of the input
field but the name
attirbute. You need to make them unique or an array for easy access in backend PHP script.
in frontend use
var $input = $('<input type="hidden" id="track_href" class="track" value="" name="track_href[]" />');
instead of
var $input = $('<input type="hidden" id="track_href" class="track" value="" name="track_href" />');
in backend
//$href is an array now
foreach($href as $v){
$tmp[] = "('$playlist_id', '".mysql_real_escape_string($v)."')";
}
$song_query = "INSERT INTO songs (playlist_id, href) VALUES ".implode(',', $tmp);