How to save flag values โ€‹โ€‹in a form in a single MySQL field?

I have a form where I have many musical genres. An artist can sing under different genres. I put genres in checkboxes. Now I need to save the values โ€‹โ€‹of the flags in one field.

Can someone help me with some piece of code as I am new to php programming?

+3
source share
5 answers

In general, you should not do this. Your database will not be normalized , and this will make it difficult to collect queries in the genre field.

, artists genres. artists_genres, artist_id a genre_id. .

, , :

 TABLE artists
 -------------

 artist_id          name             surname
 1                  Alicia           Keys
 2                  Mariah           Carey
 ...


 TABLE genres
 ------------

 genre_id           name
 1                  R&B
 2                  pop
 3                  hip hop
 4                  dance
 ...


 TABLE artists_genres
 --------------------

 artist_id          genre_id
 1                  1
 1                  2
 1                  3
 2                  1
 2                  2 
 2                  4
 ...

, :

SELECT 
    artists.name, artists.surname
FROM
    artists
INNER JOIN
    artists_genres ON (artists_genres.artist_id = artists.artist_id)
INNER JOIN
    genres ON (genres.genre_id = artists_genres.genre_id)
WHERE
    genre.name = 'pop';

, artists. , , , , .

+4

- / .

, "" "artist_genres".

+2

You can use serialize / unserialize , but you should not save serialized data to the database.

You cannot use the database functions on it (search, order, etc.), i.e.

+1
source

You can serialize data, for example:

<input type="checkbox" name="genre[]" value="Genre1"/>
<input type="checkbox" name="genre[]" value="Genre2"/>
<input type="checkbox" name="genre[]" value="Genre3"/>

PHP:

// Don't forget to escape the POST-values
$genre = serialize($_POST['genre']);
$query = "INSERT INTO database (genre) VALUES ('" . $genre . "')";
if(mysql_query($query)){
   // Success
}

You can return data using:

$genres = unserialize($serializedGenre);
+1
source

MySQL has a SET data type that could well store a set of flags in a single column.

0
source

Source: https://habr.com/ru/post/1729677/


All Articles