0

My $keywords are Design~!~Development~!~Print:

$keywordsplit = explode('~!~',$keywords); 

foreach($keywordsplit as $keysplit){

   $sqlkeyword= "INSERT INTO keywords (keyword) VALUES ('" . mysql_real_escape_string($keysplit) . "')";

}

$keywordtest = mysql_query( $sqlkeyword, $conn );

In my keywords table I'm only getting the word Print. Can someone explain to me why that is?

1

4 Answers 4

3

You have to put query inside the loop, otherwise only the last one is executed.

foreach($keywordsplit as $keysplit) {
   $sqlkeyword= "INSERT INTO keywords (keyword) VALUES ('".mysql_real_escape_string($keysplit)."')";
  $keywordtest = mysql_query( $sqlkeyword, $conn );
}

And you could also build a sql to insert multiple rows at once.

Sign up to request clarification or add additional context in comments.

1 Comment

The solution you provided puts nothing in the table.
2

What happened is that variable got overwritten. You could do something like this (and suggestion):

$raw_keyword = 'Design~!~Development~!~Print';
$keywordsplit = explode('~!~',$raw_keyword);
$values = array();
foreach($keywordsplit as $value) {
    $values[] = "('".$value."')";
}

$sqlkeyword = "INSERT INTO keywords (keyword) VALUES ".implode(',', $values);
echo $sqlkeyword; // INSERT INTO keywords (keyword) VALUES ('Design'),('Development'),('Print')

Comments

2

You are overwriting $sqlkeyword in each iteration, thus only the last "keyword" is stored. You would need to execute the statement inside the loop or write a multi-insert statement.

Comments

0

Your $sqlkeyword in foreeach will return only last value. because you put your mysql_query outside foreach. You can use this method to run mysql_query for every foreach keyword

$keywords = "Design~!~Development~!~Print";
$keywordsplit = explode('~!~',$keywords); 

foreach($keywordsplit as $keysplit) {
    $sqlkeyword = "INSERT INTO keywords (keyword) VALUES ('".mysql_real_escape_string($keysplit)."')"; 
    $keywordtest = mysql_query( $sqlkeyword, $conn );
}

or this method to save the foreach keyword as array

$keywords = "Design~!~Development~!~Print";
$keywordsplit = explode('~!~',$keywords); 
$arraykeyword = array();

foreach($keywordsplit as $keysplit) {
    $arraykeyword[] = "('".mysql_real_escape_string($keysplit)."')";
}
$sqlkeyword = "INSERT INTO keywords (keyword) VALUES " . implode( ',', $arraykeyword); 
$keywordtest = mysql_query( $sqlkeyword, $conn );

First method look simple but will consume more memory than second method

Comments

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.