在 PHP 中插入选择 2 标记 j查询数组

我已经看到许多关于这个问题的堆栈溢出线程,但我无法实现这一点,所以再次发表了这篇文章。我正在使用我想使用PHP在SQL中插入标签的地方。赞 [select2 jQuery pluginData, Data, Data]


我尝试做我通过谷歌学到的东西,好吧,我在这方面是专业化的,我是PHP的新手。请帮助'我如何在数据库中插入这个,其中显示两个单词之间,如上所述,我在,Like'


我的代码是


if(isset($_POST['submit'])) {

    $name = "Your_Name";

    $email = "Your_Email";


    $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (':name',':email',':color')");

    foreach ($data as $row)

    {

        ':name' = $name;

        ':email' = $email;

        ':color' = 'MYStatus'; //I want mention here Select2 Tags Data and insert in DB where [, (space)] every two words. like [Green, Red, Blue, Pink] 

        $stmt->execute();

    }

  }

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css">

</head>

<body>

<form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">


    <div class="form-group col-sm-6">

      <div>

        <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>

      </div>

    </div>


    <div class="form-group">

        <div class="col-lg-offset-2 col-lg-10">

            <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>

        </div>

    </div>

</form>

<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/jquery.min.js"></script>

  <script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/bootstrap.js"></script>

<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.min.js"></script>

<script type="text/javascript" language="javascript">

    if ($.fn.select2) {

      $("#select2-option").select2();

      $("#select2-tags").select2({

        tags:["Red", "Green", "Blue", "Pink"],

        tokenSeparators: [",", " "]}

      );

    }

</script>

</body>

</html>


慕工程0101907
浏览 121回答 1
1回答

holdtom

您的表单可能按如下方式发送:Array(&nbsp; &nbsp; [selectname] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => brown,Green,Blue&nbsp; &nbsp; &nbsp; &nbsp; ))因此,既然您希望将其格式化为 ,那么您可以和/或仅使用:brown, Green, Blueexplode()implode()str_replace()# Exploding, imploding$tags = implode(", ", explode(",", $_POST['selectname'][0]));# String replace would be$tags = str_replace(',', ', ', $_POST['selectname'][0]);如果您尝试拆分该字符串以单独插入每个标记,则应在逗号上使用,然后循环 .explode()explode()我可能会在那里使用删除空白空间,以防万一。另外,如果你想确保它们的格式都相同,你可能想确保每个单词都有一个大写字母作为第一个字母(你的默认值棕色全部变低,重置时第一个字母大写)。trim()ucwords()如果执行方法 1,则可以应用一个,如果在分解字符串上使用:ucfirst()trim()array_map()# A full combination of functions$tags = implode(", ", array_map(function($v){&nbsp; &nbsp; return ucfirst(trim($v));}, explode(",", $_POST['selectname'][0])));会给你字符串:Brown, Green, Blue编辑:由于您实际上是按行存储的,因此可以使用 :selectfunction getColorTags($name, $con){&nbsp; &nbsp; # Query by name, just return the color_name field though&nbsp; &nbsp; $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `name` = ?");&nbsp; &nbsp; # Execute the query with bind value&nbsp; &nbsp; $query->execute([$name]);&nbsp; &nbsp; # Loop the results&nbsp; &nbsp; while($result = $query->fetch(\PDO::FETCH_ASSOC)) {&nbsp; &nbsp; &nbsp; &nbsp; # Store the tags&nbsp; &nbsp; &nbsp; &nbsp; $row[] = $result['color_name'];&nbsp; &nbsp; }&nbsp; &nbsp; # Return the tags or an empty array&nbsp; &nbsp; return (isset($row))? $row : [];}使用方法:# Fetch the tags by name, make sure to inject the database connection$tags = getColorTags('Some Name', $con);# Print out the arrayprint_r($tags);编辑 #2要在同一页面上同时执行此操作,您只需使用:json_encode()<?phpfunction insertTags($data, $email, $name, $con){&nbsp; &nbsp; $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (?,?,?)");&nbsp; &nbsp; foreach ($data as $string) {&nbsp; &nbsp; &nbsp; &nbsp; # Explode and filter the tags from the js&nbsp; &nbsp; &nbsp; &nbsp; $arr = array_filter(array_map('trim', explode(',', $string)));&nbsp; &nbsp; &nbsp; &nbsp; # Loop the "selectname"&nbsp; &nbsp; &nbsp; &nbsp; foreach($arr as $tag) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Execute all the rows&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute([$name, $email, $tag]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}# This fetches using the email as the primary keyfunction getColorTags($email, $con){&nbsp; &nbsp; # Query by name, just return the color_name field though&nbsp; &nbsp; $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `email` = ?");&nbsp; &nbsp; # Execute the query with bind value&nbsp; &nbsp; $query->execute([$name]);&nbsp; &nbsp; # Loop the results&nbsp; &nbsp; while($result = $query->fetch(\PDO::FETCH_ASSOC)) {&nbsp; &nbsp; &nbsp; &nbsp; # Store the tags&nbsp; &nbsp; &nbsp; &nbsp; $row[] = $result['color_name'];&nbsp; &nbsp; }&nbsp; &nbsp; # Return the tags or an empty array&nbsp; &nbsp; return (isset($row))? $row : [];}# Pull these out so you can use them in general$name = "Your_Name"; // Assuming this is from the session$email = "Your_Email"; // Assuming this is from the session# Here is where you insertif(isset($_POST['submit'])) {&nbsp; &nbsp; # This will insert your tags separately on new rows&nbsp; &nbsp; insertTags($_POST['selectname'], $email, $name, $con);&nbsp; &nbsp; # This will pull them back from the database (helpful if they already have some in there)&nbsp; &nbsp; $tags = getColorTags($email, $con);}# Here you check if there are tags already generated after submission,# if not, then pull them.if(!isset($tags))&nbsp; &nbsp; $tags = getColorTags($email, $con);?><!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css"></head><body><form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">&nbsp; &nbsp; <div class="form-group col-sm-6">&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <div class="col-lg-offset-2 col-lg-10">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></form><script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/jquery.min.js"></script>&nbsp; <script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/bootstrap.js"></script><script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.min.js"></script><script type="text/javascript" language="javascript">&nbsp; &nbsp; if ($.fn.select2) {&nbsp; &nbsp; &nbsp; &nbsp; $("#select2-option").select2();&nbsp; &nbsp; &nbsp; &nbsp; $("#select2-tags").select2({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Now use this native function to echo the array back to JS&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tags: <?php echo json_encode($tags) ?>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tokenSeparators: [",", " "]}&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP