Php 插入查询-在数据数组中循环?
我有一系列的名字。我的表格结构是:Php 插入查询-在数据数组中循环?,php,mysql,Php,Mysql,我有一系列的名字。我的表格结构是: id | name 将数组中的每个名称插入表中单独一行的最佳方法是什么 id | name 1 | John 2 | James 我在考虑在PHP中循环数组,但一定有更好的方法吗?使用MySQli例如: $DB = new mysqli ("Server","username","password","database"); $Array = array("Daryl", "AnotherName"); foreach ($Array AS $Nam
id | name
将数组中的每个名称插入表中单独一行的最佳方法是什么
id | name
1 | John
2 | James
我在考虑在PHP中循环数组,但一定有更好的方法吗?使用MySQli例如:
$DB = new mysqli ("Server","username","password","database");
$Array = array("Daryl", "AnotherName");
foreach ($Array AS $Names){
$Query = $DB->prepare("INSERT INTO Table (Name) VALUES (?)");
$Query->bind_param('s',$Names);
$Query->execute();
$Query->close();
}
最好的方法是使用foreach在数组中循环以获取各个值。。然后在循环到下一个值之前对当前值执行插入 使用MySQli例如:
$DB = new mysqli ("Server","username","password","database");
$Array = array("Daryl", "AnotherName");
foreach ($Array AS $Names){
$Query = $DB->prepare("INSERT INTO Table (Name) VALUES (?)");
$Query->bind_param('s',$Names);
$Query->execute();
$Query->close();
}
最好的方法是使用foreach在数组中循环以获取各个值。。然后在循环到下一个值之前对当前值执行插入 对@Daryl Gill的一个小改进,用于
prepare
更好的实践
// List of names to insert
$names = array("Daryl", "AnotherName");
// Prepare once
$sh = $db->prepare("INSERT INTO tblname (Name) VALUES (?)");
foreach ($names AS $name){
$sh->bind_param('s', $name);
$sh->execute();
}
// Free resource when we're done
$sh->close();
@Daryl Gill的一个小改进,用于
准备
更好的实践
// List of names to insert
$names = array("Daryl", "AnotherName");
// Prepare once
$sh = $db->prepare("INSERT INTO tblname (Name) VALUES (?)");
foreach ($names AS $name){
$sh->bind_param('s', $name);
$sh->execute();
}
// Free resource when we're done
$sh->close();
这将是使用准备好的语句和绑定参数的最佳位置。定义“最佳”。您当前的方法是否遇到任何问题?循环数组以创建一个多值
INSERT
statement,例如,INSERT INTO tableName VALUES(1,'John'),(2,'James')
这将是使用准备好的语句和绑定参数的最佳位置。定义“best”。您目前的方法是否遇到任何问题?循环数组以创建一个多值的INSERT
statement,例如,INSERT-INTO-tableName-VALUES(1,'John'),(2,'James')
嗯,我不喜欢mysqli(大多数时候我使用PDO)。“s”表示第一个参数是字符串类型。看:嗯,我不是mysqli的粉丝(大多数时候我都使用PDO)。“s”表示第一个参数是字符串类型。见: