我有一个包含name和id的数组,我想将这些东西插入表中,但我只能插入11行中的四行
我不知道我犯了错误的地方,
这是我的阵列:
Array (
[0] => Array ( [id] => 6143310130 [name] => )
[1] => Array ( [id] => 3310773561 [name] => Arau )
[2] => Array ( [id] => 1127328875 [name] => Womens )
[3] => Array ( [id] => 9847224704 [name] => shoulder )
[4] => Array ( [id] => 7099570428 [name] => Swapna )
[5] => Array ( [id] => 5263908918 [name] => Top Hospitals India )
[6] => Array ( [id] => 7504483424 [name] => Wodsjls )
[7] => Array ( [id] => 2051860883 [name] => Star )
[8] => Array ( [id] => 4582742687 [name] => Manipal chand )
[9] => Array ( [id] => 1024875457 [name] => lokpal )
[10] => Array ( [id] => 7120814620 [name] => Shiney )
[11] => Array ( [id] => 8367976928 [name] => suma )
)
我的sql查询如下:
foreach ($ret as $key) {
if(mysqli_query($con,"insert ignore INTO AdsAccount(accountID,accountName) VALUES ('$key[id]','$key[name]')")) {
echo "success";
}
}
答案 0 :(得分:1)
我猜你的SQL语法中有一个拼写错误。在变量中定义SQL查询字符串,如下所示,没有'ignore'(忽略语句超出错误):
$sql = 'insert INTO AdsAccount(accountID,accountName) VALUES ('.$key[id].','.$key[name].')';
使用循环为插入创建查询:
$i = 0;
$sql = 'insert INTO AdsAccount(accountID,accountName) VALUES';
foreach($array as $key) {
$sql .= '('.$key['id'].','.$key['name'].')';
if($i < count($array) - 1) {
$sql .= ",\n";
}
$i++;
}
$sql .= ';';
mysqli_query($con, $sql);
可能必须拆分查询,因为只能同时进行四次插入。在这种情况下使用模数运算。
编辑: 更好的方法是使用PHP数据对象(PDO)扩展中的预准备语句。
为此,您需要PDO连接
$dbh = new PDO('mysql:host=<dbhost>;dbname=<dbname>', <dbuser>, <dbuserpass>);
然后您可以执行以下操作:
$stmt = $dbh->prepare("INSERT INTO AdsAccount (accountID , accountName ) VALUES (:accountID, :accountName)");
// $id and $name work as references
$stmt->bindParam(':accountID', $id, PDO::PARAM_INT);
$stmt->bindParam(':accountName', $name, PDO::PARAM_STR);
foreach($array as $key) {
$id = $key['id']; //set the reference for id
$name = $key['name']; //set the reference for name
$stmt->execute(); //execute the statement
}
找到详细说明