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

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@user641086 you're welcome. Hope you learned some good practice from my answer, to use it with every query you run in your scripts.
1

insert multiple rows via a php array into mysql

Comments

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)."')");

Comments

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());

Comments

-1

You can use this:

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

Better syntax to understand :)

2 Comments

that's the syntax for UPDATE query. Even if it would work I would never use it this way!
@krike in fact, it's quite handy to have similar syntax for both types, lets you reuse your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.