【问题标题】:Insert select2 tags jQuery array in PHP在 PHP 中插入 select2 标签 jQuery 数组
【发布时间】:2020-02-17 12:58:25
【问题描述】:

我在 stackoverflow 上看到了很多关于这个问题的帖子,但我无法做到这一点,所以再次发布了这篇文章。我正在使用select2 jQuery plugin,我想使用 PHP 在 SQL 中插入标签。喜欢[Data, Data, Data]

我尝试做我通过谷歌学习的东西,我在这方面很专业,我是 PHP 新手。 请帮助'我如何在 DB 中插入这个在两个单词之间显示,,如上所述我在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>

【问题讨论】:

    标签: php jquery html arrays jquery-select2


    【解决方案1】:

    您的表单可能是这样发送的:

    Array
    (
        [selectname] => Array
            (
                [0] => brown,Green,Blue
            )
    
    )
    

    因此,既然您希望将其格式化为brown, Green, Blue,那么您可以使用explode()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() 以确保每个单词的第一个字母 都是大写的(您的默认值 brown 都是小写的,并且重置首字母大写)

    如果您执行方法 1,则可以应用 ucfirst()trim(),如果您在分解后的字符串上使用 array_map()

    # A full combination of functions
    $tags = implode(", ", array_map(function($v){
        return ucfirst(trim($v));
    }, explode(",", $_POST['selectname'][0])));
    

    会给你字符串:

    Brown, Green, Blue
    

    编辑:

    由于您实际上是按行存储,因此您可以使用 select 取回数组:

    function getColorTags($name, $con)
    {
        # Query by name, just return the color_name field though
        $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `name` = ?");
        # Execute the query with bind value
        $query->execute([$name]);
        # Loop the results
        while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
            # Store the tags
            $row[] = $result['color_name'];
        }
        # Return the tags or an empty array
        return (isset($row))? $row : [];
    }
    

    使用方法:

    # Fetch the tags by name, make sure to inject the database connection
    $tags = getColorTags('Some Name', $con);
    # Print out the array
    print_r($tags);
    

    编辑#2

    要在同一个页面上同时进行,您只需使用json_encode()

    <?php
    function insertTags($data, $email, $name, $con)
    {
        $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (?,?,?)");
    
        foreach ($data as $string) {
            # Explode and filter the tags from the js
            $arr = array_filter(array_map('trim', explode(',', $string)));
            # Loop the "selectname"
            foreach($arr as $tag) {
                # Execute all the rows
                $stmt->execute([$name, $email, $tag]);
            }
        }
    }
    # This fetches using the email as the primary key
    function getColorTags($email, $con)
    {
        # Query by name, just return the color_name field though
        $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `email` = ?");
        # Execute the query with bind value
        $query->execute([$name]);
        # Loop the results
        while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
            # Store the tags
            $row[] = $result['color_name'];
        }
        # Return the tags or an empty array
        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 insert
    if(isset($_POST['submit'])) {
        # This will insert your tags separately on new rows
        insertTags($_POST['selectname'], $email, $name, $con);
        # This will pull them back from the database (helpful if they already have some in there)
        $tags = getColorTags($email, $con);
    }
    # Here you check if there are tags already generated after submission,
    # if not, then pull them.
    if(!isset($tags))
        $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();">
        <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({
                // Now use this native function to echo the array back to JS
                tags: <?php echo json_encode($tags) ?>,
                tokenSeparators: [",", " "]}
            );
        }
    </script>
    
    </body>
    </html>
    

    【讨论】:

    • 非常感谢您能在同一线程中再次帮助我,无法在此 select2 框中制作 &lt;option&gt;Green&lt;/option&gt; 喜欢标签。我目前正在从 js 代码中获取选项。 or 我如何在 php 中编写代码,显示 tags:["Red", "Green", "Blue", "Pink"], 像这样从 db 中获取,其中表名为 dummy
    • 哦,您想在保存标签后将标签作为数组获取吗?如果是这种情况,则取决于您如何保存标签。如果您将所有标签保存在一行或多个中,那就不同了。
    • 我将标签保存在每一列中
    • 我已经演示了基于每行示例的提取。
    • 哦,我明白你想做什么(有点)。 $tags 如果您试图将它们显示回该 javascript 中,则不应内爆(推测 javascript 位于与 php 相同页面上的页面的 html 中)。我将针对该更改进行编辑。
    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 2023-02-16
    • 2017-01-24
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多