SQL >> Database >  >> RDS >> Mysql

PHP/MySQL — hoe voeg ik meerdere tags toe

je kunt explode() gebruiken

Om een array met tags te krijgen, gescheiden door komma's

$tag_string = "t1, t2, t3"; $tags = explode(",", $tag_string ); echo $tags[0]; // t1 echo $tags[1]; // t2 

Daarna kun je door de array loopen om in de database in te voegen

Je wilt misschien ook dat je Create Query UNIQUE bevat

CREATE TABLE tags ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, tag VARCHAR(255) NOT NULL, PRIMARY KEY (id), UNIQUE(`tag`) ); 

Op deze manier zul je niet twee tags met dezelfde naam hebben. Kijk hier voor verdere uitleg over de UNIQUE-syntaxis

Daar gaat code zonder te testen xD

//Assuming you have already added the question and the mysql_insert_Id() == 1 //where mysql_insert_Id() is the last id added to the question table if (isset($_POST['tags'])){ $tags = explode(",", $_POST['tags']); for ($x = 0; $x < count($tags); $x++){ //Due to unique it will only insert if the tag dosent already exist mysql_query("INSERT INTO tag VALUES(NULL, {$tags[x]})"); //Add the relational Link mysql_query("INSERT INTO question_tag VALUES(NULL, (SELECT tags.Id FROM tags WHERE tags.tag = {$tags[x]}), 1)"); } } 
  1. Meerdere MySQL-tabellen joinen voor ticketrapportage

  2. Meertalige tekstvelden opslaan in MySQL met PHP

  3. Een MySQL-resultaatset transponeren in PHP

  4. Komma in PHP/MySQL lezen als regeleinde of br-tag