Help parse the following PHP Function code, for example, why this is so:

$field .= $val['name']."='".mysql_real_escape_string($val['val'])."',"; 

etc.

 <?php /** * * @param string $tblName имя Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹ ΠΊΡƒΠ΄Π° вставляСм Π΄Π°Π½Π½Ρ‹Π΅ * @param array $fields * ΠΌΠ½ΠΎΠ³ΠΎΠΌΠ΅Ρ€Π½Ρ‹ΠΉ массив ΠΏΠΎΠ»Π΅ΠΉ ΠΈΠΌΠ΅ΡŽΡ‰ΠΈΠΉ Π²ΠΈΠ΄ * array(array('name'=>'имя поля Π² Π±Π°Π·Π΅','val'=>'Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅'), * array('name'=>'имя поля2 Π² Π±Π°Π·Π΅','val'=>'Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅2')) */ function Add($tblName,$fields) { if(is_array($fields)) { foreach ($fields as $val) $field .= $val['name']."='".mysql_real_escape_string($val['val'])."',"; $field = substr($field,0,-1); if(mysql_query("INSERT INTO $tblName SET $field ;")) { $companyId = mysql_insert_id(); return $companyId; } else return false; } else return false; } ?> 

    1 answer 1

    In my opinion, everything is already written in the description of the function. Suppose we pass an array to a function:

     array(array('name'=>'field1','val'=>'5'),array('name'=>'field2','val'=>'33')) 

    In the function in the loop, we go around this array

     foreach ($fields as $val) $field .= $val['name']."='".mysql_real_escape_string($val['val'])."',"; 

    At the end, we will get a type string in the $ field variable

     "field1='5',field2='33'" 

    and in the next line we will execute INSERT into the database

     INSERT INTO $tblName SET field1='5',field2='33' ; 

    The mysql_insert_id () function will return the id of the last inserted record, i.e. the result of the function will be the id of the string that we have interleaved or false in all other cases.