0

Hey guys not looking for explanation on why its inserting twice, I understand it loops from ['0'] to ['1'] just want to figure out how to stop my insert after the first try...

$trans=array('hello' => 'allo',
             'bye' => 'salut'), 
$sql = "INSERT INTO trans (en, fr) values ";    
$valuesArr = array();
foreach ($trans as $key => $value){
    $en = mysql_real_escape_string( $key );
    $fr = mysql_real_escape_string( $value );
    $valuesArr[] = "('$en', '$fr')";
}

$sql .= implode(',', $valuesArr);

mysql_query($sql) or exit(mysql_error());

My actual question is can i stop the foreach as soon as it goes through the array using break;?

3
  • "'bye' => 'salut')," - syntax error - no semicolon, you have colon instead Commented Mar 3, 2014 at 21:13
  • Is this a legacy application? mysql_query shouldn't be used in new code because it's been deprecated, is dangerous if used incorrectly, and is being removed from future versions of PHP. A modern replacement like PDO is not hard to learn. A guide like PHP The Right Way has a number of recommendations as to how to keep your application up-to-date. Commented Mar 3, 2014 at 21:18
  • not legacy just trying to save old array in db, wanna automate it for a one time run. Still havnt figure out my issue. Commented Mar 3, 2014 at 21:19

2 Answers 2

2

It is inserting two rows at one time (it isn't inserting twice as you mentioned) because your $trans array contains two items which are iterating in foreach loop. After the foreach loop the $valuesArr is equal to:

[0] => ('hello', 'allo')
[1] => ('bye', 'salut')

Then you are using implode to join $valuesArr elements with comma as separator and concat with $sql variable which produce final SQL query:

INSERT INTO trans(en, fr) values ('hello', 'allo'),('bye', 'salut')

I think I don't need to explain what this query do.

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

Comments

1

You could use a counter to control the building of your insert - assuming you want the 2nd of the 2 inserts

$trans=array('hello' => 'allo','bye' => 'salut');
$sql = "INSERT INTO trans (en, fr) values ";    
$valuesArr = array();

$i = 0;
foreach ($trans as $key => $value){

    if ($i > 0) {
        $en = mysql_real_escape_string( $key );
        $fr = mysql_real_escape_string( $value );
        $valuesArr[] = "('$en', '$fr')";
    }
    $i++;

}

$sql .= implode(',', $valuesArr);

2 Comments

i only want the inital
By making $i = 1 it stop at the first and resolved my issue Thanks

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.