我正在尝试将多个字段添加到同一个表中。当我回显$ url时,我可以看到url值,但是没有为所有url存储数据,它只是第一个url。
例如,公司网站可以有多个网址。foreach ($_POST['url'] as $url) {
//$url = $_POST['url'];
echo $url;
$sql_insert_url="insert into url_table(url, company_name)
values ('$url', '$comp_name')";
}
我的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:
$(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++;
});
任何有关此的帮助将不胜感激。另外,请建议一些好的php编辑器,它将帮助我快速找出php漏洞,内存泄漏等。
答案 0 :(得分:0)
INSERT
允许在VALUES
关键字后面设置多组值。此代码将所有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";
答案 1 :(得分:0)
我在这里找到答案: Inserting multiple array values in mySQL database
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.