简体   繁体   English

将多个值插入同一表字段

[英]Insert multiple values to the same table field

I'm trying to add multiple fields to the same table. 我试图将多个字段添加到同一张表。 when i do echo $url, i can see the url values, but the data is not getting stored for all urls, it's the first url only. 当我回显$ url时,我可以看到url值,但是并没有为所有url存储数据,它只是第一个url。

example, a company website can have multiple urls. 例如,公司网站可以有多个网址。

foreach ($_POST['url'] as $url) {
   //$url = $_POST['url'];
    echo $url;
    $sql_insert_url="insert into url_table(url, company_name) 
          values ('$url', '$comp_name')";
}

my html: 我的html:

<div id="allurl">
        <div id="newurl">
            <label for="companyurl" >Company URL #1</label>
            <input type="text" name="url[]" id="url" maxlength="300" />
            <input type='button' value='Add' id='addurl' />
            </p>
        </div>

javascript: javascript:

  $(document).ready(function(){
    var counter=2;
    $("#addurl").click(function(){


        var n= $(document.createElement('div')).attr("id", 'newurl' + counter);

        n.after().html('<p><label>Company URL #' + counter + ' </label>' + '<input type="text" name="url[]" value="url' + counter + '" id="url' + counter + '" value="" />' + '<input type="button" name="remove'  +'" id="removeurl' +  '" value="Remove" /></p>');
        n.appendTo("#allurl");
        counter++;

    });

any help with this will be appreciated. 任何帮助,将不胜感激。 also, please suggest some good php editor that will help me figure out the php bugs, memory leaks etc quickly. 另外,请建议一些好的php编辑器,它将帮助我快速找出php错误,内存泄漏等。

INSERT allows multiple sets of values after the VALUES keyword. INSERT允许在VALUES关键字之后使用多组值。 This code combines all the URLs into a list of like this: 这段代码将所有URL合并为一个类似这样的列表:

$values = implode(',', array_map(function($x) use ($comp_name) {
    return "('" . mysql_real_escape_string($x) . "', '$comp_name')"; },
  $_POST['url']));
$sql_insert_url = "insert into url_table(url, company_name) values $values";

I found the answer here: Inserting multiple array values in mySQL database 我在这里找到了答案: 在mySQL数据库中插入多个数组值

so all i needed to do is 
    $sql = "insert into win_url(url, company) values";
        foreach ($_POST['url'] as $url) {
         $sql .=  "('".$url."','" . $comp_name. "'),";

           }

     $sql = substr($sql, 0, -1); // remove trailing comma
      mysql_query($sql);

that's it.. magic... it works. thanks to me. i'm the best.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM