Question

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;?

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top