如何使用Select2创建新标签并将其保存到数据库 [英] How to create new tags with Select2 AND save to database

查看:168
本文介绍了如何使用Select2创建新标签并将其保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在选择2方面遇到了很大的困难.我希望用户能够在选择列表中进行搜索,并且在找不到搜索结果时也可以创建新标签.创建新标签不是问题.最重要的是-将新闻标签插入数据库中,这在大多数论坛中都被忽略了,这是令人惊讶的.我是Select2的新手,所以我想举一个完整的例子.而且我正在这个项目上使用PHP,因此,如果有一种方法可以用PHP做到这一点,那将真的很有帮助.

So, I'm having a real hard time with Select2. I want users to be able to search through a select list and also create new tags when no search result is found. Creating new tags is not the problem. The main thing - and surprisingly overlooked in most forums - is to INSERT the news tags to the Database. I'm new to Select2, so I'd like to have a full example. And I'm using PHP on this project, so, if there is a way to do this with PHP it would be really helpful.

这是我的代码:

$('#caracteristicas').select2({theme:'bootstrap', width:null, placeholder:'Selecione', allowClear:true})

<?php 
$q = mysqli_query($con, "select id, descricao from caracteristicas");
if(mysqli_num_rows($q)>(0))
{
?>
<div class="form-group">  
	<label for="caracteristicas">Selecione um  ou mais resultados</label>
	<select name="caracteristicas[]" id="caracteristicas" class="form-control" multiple="multiple">
		<option value="">Selecione</option>
		<?php                    
		while($linhas = mysqli_fetch_array($q)):
		?>
		<option value="<?=$linhas["id"]?>">
          <?=strlen($linhas["descricao"])>50 ? substr($linhas["descricao"], 0, 50)."..." : $linhas["descricao"]?>
        </option>
		<?php endwhile;?>
	</select>
</div>
<?php } mysqli_close($con);?>

注意:我正在使用Select2 4.0

Note: I'm using Select2 4.0

推荐答案

只需弄清楚如何做到这一点.我注意到用户创建的标签没有ID,这意味着选项值将是字符串而不是数字.因此,我要做的就是告诉PHP以不同的方式处理字符串值.这是我解决此问题的方法:

Just figured out how to do this. I've noticed that tags created by user don't have an id, wich means, the option value will be a string, instead of a number. So, all I had to do was tell PHP to handle string values in a different way. Here's how I solved this:

for($i=0; $i<count($opcoes); $i++)
{
	if(!is_numeric($opcoes[$i]))
	{
		if(!mysqli_query($con, "INSERT INTO `atividades`(`id`, `descricao`) VALUES (NULL, '".$opcoes[$i]."')"))
		{
			$msg_caracteristicas[$i] = "A atividade n&atilde;o foi cadastrada, <strong>erro <a href='http://randomurl.com' target='_blank'>#".mysqli_errno($con)."</a></strong> - \"".mysqli_error($con)."\"";	
		}
		else
		{
			echo "<script>alert('deu certo');</script>";	
		}
	}
}

这篇关于如何使用Select2创建新标签并将其保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆