Reputation: 25
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;?
Upvotes: 0
Views: 136
Reputation: 169
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);
Upvotes: 1
Reputation: 1489
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.
Upvotes: 2