I have a small problem :) I was searching the web but didn\'t find any solutions.
I have a value like this (got it from $_GET[])
tag1, tag2, tag3, tag4
Try this for size: (combining ideas from a number of people who almost got it right).
$values = array(
33=>'tag1'),
33=>'tag2'),
33=>'tag3'),
);
$sql = "INSERT INTO table (id, value) VALUES ";
$count=0;
foreach ($values as $id=> $value)
{
if ($count++ > 0)
$sql .= ',';
$sql .= "($id, '$value')";
}
$query = mysql_query($sql, $db);
$id=33;
$tag=$_GET['tag'];
$tag_Split= explode(",", $tag);
$cnt=count($tag_Split);
for($i=0;$i<$cnt;$i++)
{
mysql_query("insert into tag_table(id,tag)
values ($id, $tag_Split[$i])");
}
Use explode()
function to split the string
$tag = "tag1, tag2, tag3";
$pieces = explode(", ", $tag);
SQL query would be
INSERT INTO myTable VALUES ($pieces[0],$pieces[1],$pieces[2]);
Good Luck!!!
You can do an INSERT INTO
with multiple values:
INSERT INTO table (tag) VALUES ('tag1', 'tag2', 'tag3');
Make sure, you properly escape your input (if user suplied) to prevent SQL injection. You can use mysql_escape_string()
for this.
Edit: To get these values, you can do:
$values = explode(",", $_GET['your_param']);
foreach($values as $idx => $val) {
$values[$idx] = mysql_real_escape_string(trim($val));
}
mysql_query("INSERT INTO table (tag) VALUES (".implode(",", $values).");");
I would convert your comma-delimited tags into an array, then loop through the array to do your inserts.
$data_array=explode(",",$tag); // converts tags to an array based on the comma
// loop through each item in the array
foreach($data_array as $one_tag){
// Get rid of the space you have in your tag string
$one_tag=trim($one_tag);
// Do whatever sanitization you need to do to your data, for example...
$one_tag=mysql_real_escape_string($one_tag);
// Insert into the database
mysql_query("INSERT INTO table SET tag='$one_tag'");
}
You can make this more efficient using Prepared Statements, but it kept this example simple.
This will work out according to your result
$tagData = array();
$tagList = explode(",","tag1,tag2,tag3,tag4");
foreach ($tagList as $key=>$value) {
$tagData[] = '("' . $key . '", "' . $tagList[$key] . '")';
}
$query = 'INSERT INTO tags (id,tag) VALUES' . implode(',', $tagData);
echo $query;die;
mysql_query($query);