Now I found a code that I modified and it is doing what I want (almost). The code is generating the music genre from a table of songs (with a lot of info) called table_genre with the fields genre_id and genre_name.
These are included in a form as checkboxes. The user can check one or more boxes of the genres that suit the song.
Then I want to input this into my table called songs_genre, but right now I only have it on my screen separated with comma.
//initialize
$song_genre = count($_POST['song_genre']) ? $_POST['song_genre'] : array();
//echo out the choices separated by a comma
echo count($song_genre) ? implode(', ',$song_genre) : 'Nothing!';
I picked code from something I found when I googled it. But I want my output to be inserted into my db called songs_genre. Here I like to insert the song_genre from the form and also one called $song_id so the genres selected are connected to the song that is used on the actual form.
Can anyone tell me how to change the code above, so it is inserted as separated lines together with the song_id into my table called song_genre
If the song is $song_id=32. The genre is rock (song_genre 5), instrumental (song_genre 12).
Then I would like them inserted into my table (songs_genre) as :
//initialize
$song_id = (int)$_POST['song_id']; // I imagine this is your song id anyways ...
// now song_id is either a positive int or it is 0
$song_genre = count($_POST['song_genre']) ? $_POST['song_genre'] : array();
// now song_genre is either an empty array, or an array of potentially bad values,
// so you'd still need to cleanse them
if(empty($song_genre) || $song_id ===0)
// fail - send user away or do something else
foreach($song_genre as $genre){
// do the equivalent of ....
$sql = 'INSERT into song_genres (`song_id`,`song_genre`) values ( '. $song_id .','. (int)$genre .')';
// send your query into your db
// some debug to prove everything is named correctly
echo $sql;
}
All this typecasting with (int) could be avoided by simply using PDO prepared statements to protect your db, but in order to answer your immediate question – that is roughly what you need to achieve.
That one didn’t work. Nothing was inserted or echoed.
My one did echo the selected arrays from the form like 1, 5, 17.
But I don’t know how to make that one insert the selected ones into separate ones.
It wasnt an attack, pull the claws back.
It was simply a statement that your code block was leading the OP down the path of creating a looped query. Not that you omitted a query.
Not overwhelming the OP is fine, but lets avoid suggesting bad habits?
As far as ‘go on then’…to borrow your own structure
foreach($song_genre as $genre)
$values[] = "(".$song_id.",".$genre.")";
$sql = 'INSERT into song_genres (`song_id`,`song_genre`) values '.implode(',',$values);