-1

When i try to insert array with another string value to database it give Column count doesn't match value count error. My code given bellow any explanation why this error occurring

$Skills = "java,php";
$memberId ="1";
$wordArray = explode(",", $Skills);
$query = "INSERT INTO tempskill (skill,memberId) VALUES ('" .implode("'),  ('", $wordArray). "'  , '".$memberId."' ) ";
echo  $Skills;                   

mysql_query($query) or die ('Error :' . mysql_error());

this code output is - java,C#Error :Column count doesn't match value count at row 1

Chara
  • 31
  • 10
  • Print your query by put an echo on $query and run the query on mysql terminal and check the error – Mayank Pandeyz Jan 03 '17 at 07:42
  • Don't save CSV in a column http://stackoverflow.com/questions/41304945/best-type-of-indexing-when-there-is-like-clause/41305027#41305027 http://stackoverflow.com/questions/41215624/sql-table-with-list-entry-vs-sql-table-with-a-row-for-each-entry/41215681#41215681 – e4c5 Jan 03 '17 at 07:44
  • Thanks for your reply when i echo query it gives this - INSERT INTO tempskill (skill,memberId) VALUES ( 'abc'), ('def' , '1' ) Error :Column count doesn't match value count at row 1 – Chara Jan 03 '17 at 07:49
  • MemberID for `abc` is not set. DO you see it? – u_mulder Jan 03 '17 at 07:50
  • Yes when use SQL like this it work INSERT INTO tempskill (skill,memberId) VALUES ( 'abc' , '1' ), ('def', '1') but the problem is how to pass like this with explode – Chara Jan 03 '17 at 07:55

1 Answers1

1

To add memberId to each pair of inserted values you should use:

$query = "INSERT INTO tempskill (skill,memberId) VALUES ('" .implode("', '" . $memberId . "'),  ('", $wordArray) . "', '" . $memberId . "')";
// echoes `INSERT INTO tempskill (skill,memberId) VALUES ('java', '1'),  ('php', '1')`

But

  1. mysql extension is outdated and removed in php7.
  2. Such code is vurnerable to sql injections.

So, I advise you to move to PDO/mysqli apis and prepared statements. More info here.

Community
  • 1
  • 1
u_mulder
  • 54,101
  • 5
  • 48
  • 64