0
votes

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


// 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
Try not passing the id value. $testsql = "INSERT INTO table1 ( name) VALUES ('".$arry."')"; - Ravinder Reddy
do not pass an empty string for the id column, you may either pass NULL or your omit the column altogether - ahmad

2 Answers

1
votes

Change the line

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

to

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

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')