1
$db = mysql_connect("localhost","root","123");
mysql_select_db("website_categorization") or die("\n error selecting database" );
$keyword_array = preg_split('/[\s,]+/', $tag);                              
foreach($keyword_array as $tag1)                                                      
{
    mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,$tag1)");
}

echo "\nAffected rows are ".mysql_affected_rows()."\n";
mysql_close($db);

Can u tell me what is the problem with this code??...I intend to insert rows into the category_keyword table from an array $keyword_array. I get errors "Affected rows are -1" and insertion does not work

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
gks
  • 65
  • 9

5 Answers5

1

insert multiple rows via a php array into mysql

Community
  • 1
  • 1
miqbal
  • 2,213
  • 3
  • 27
  • 35
1

You should quote and escape string values.
You should also handle errors, to be notified of them.
You should also write distinct statements, to be able to read your code later (as well as let others to read it).

$tag1 = mysql_real_escape_string($tag1);
$sql  = "INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

You should quote and escape your string columns

$tag1 = mysql_real_escape_string($tag1); mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')");

You should also handle the mysql query errors to know why the query get failed. With the current code you never know why it is failing.It is better to handle mysql errors.

mysql_query('Your query') or trigger_error(mysql_error());
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
0

You need to encapsulte the string $tag in a query, otherwise mysql will think its a column name

  mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'".mysql_real_escape_string($tag1)."')");
Elijan
  • 1,406
  • 1
  • 8
  • 11
-1

You can use this:

mysql_query("INSERT INTO category_keyword SET ID_Category=2, Keyword=".$tag1.");

Better syntax to understand :)

Blagomir
  • 253
  • 2
  • 9