如何将php数组插入mysql表中

时间:2022-09-25 20:11:41

I have an php array that im trying to insert into a mysql table without success, The table structure has two fields, id (int auto increment primary key), and name (varchar), the code is :

我有一个php数组,我试图插入到mysql表中但没有成功,表结构有两个字段,id(int auto increment primary key)和name(varchar),代码是:

<?php


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//get values for array
$domains_test = $client->sites_web_domain_get($session_id, array('domain' => 
'%'));




foreach($domains_test as $domains) { 

 $arr = explode('.', $domains['domain']);
 unset($arr[0]);
$arry = implode('.', $arr);


$testsql = "INSERT INTO table1 (id, name) VALUES ('','".$arry."')";

if (mysqli_query($conn, $testsql)) {
echo "New record created successfully";
} else {
echo "Error: " . $testsql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

}

?>

The query inserts the first value into the table, but I get the following error :

查询将第一个值插入表中,但是我收到以下错误:

> New record created successfully
Error: INSERT INTO table1 (id, name) VALUES ('','john')
Error: INSERT INTO popular_domains2 (id, name) VALUES ('','fred')
Error: INSERT INTO popular_domains2 (id, name) VALUES ('','james')

The records I am inserting may contain duplicate values. Thanks for your help!

我插入的记录可能包含重复值。谢谢你的帮助!

2 个解决方案

#1


1  

Change the line

改变线

$testsql = "INSERT INTO table1 (id, name) VALUES ('','".$arry."')";

to

$testsql = "INSERT INTO table1 (name) VALUES ('".$arry."')";

#2


0  

As per your post id is auto increment and primary key So why you use INSERT INTO table1 (id, name) VALUES ('','john') .this is wrong because I'd field auto increment automatically not manual. So just removed the query and paste it INSERT INTO table1 ( name) VALUES (''john')

根据你的帖子ID是自动增量和主键所以为什么你使用INSERT INTO table1(id,name)VALUES('','john')。这是错误的,因为我自动增加字段自动增量而不是手动。所以只需删除查询并粘贴它INSERT INTO table1(name)VALUES(''john')

#1


1  

Change the line

改变线

$testsql = "INSERT INTO table1 (id, name) VALUES ('','".$arry."')";

to

$testsql = "INSERT INTO table1 (name) VALUES ('".$arry."')";

#2


0  

As per your post id is auto increment and primary key So why you use INSERT INTO table1 (id, name) VALUES ('','john') .this is wrong because I'd field auto increment automatically not manual. So just removed the query and paste it INSERT INTO table1 ( name) VALUES (''john')

根据你的帖子ID是自动增量和主键所以为什么你使用INSERT INTO table1(id,name)VALUES('','john')。这是错误的,因为我自动增加字段自动增量而不是手动。所以只需删除查询并粘贴它INSERT INTO table1(name)VALUES(''john')