22Feb/091
Build MySQL insert Query from Array that contains fields and values
The following function takes table name, and array where its keys are the table fields and it's values are the values to insert in each field, it constructs the MySQL Query based on the input and executes it to insert the data.
function insertRow($table_name, $input_array){ $link = mysql_connect(SERVER, USER, PASS); mysql_select_db(DATABASE, $link); $SQL = "INSERT INTO $table_name "; $fields = "("; $values = "("; foreach ($input_array as $k => $v) { $fields .= "`$k` ,"; $values .= "'$v' ,"; } $fields .="#"; $values .="#"; $fields = explode(",#", $fields); $fields = $fields[0]; $values = explode(",#", $values); $values = $values[0]; $fields .= ")"; $values .= ")"; $SQL .= $fields . " VALUES " . $values; mysql_query($SQL); mysql_close($link); }
17Feb/092
List array Recursively in PHP
Code :
function listArrayRecursive($array_name, $ident = 0){ if (is_array($array_name)){ foreach ($array_name as $k => $v){ if (is_array($v)){ for ($i=0; $i < $ident * 10; $i++){ echo " "; } echo $k . " : " . "<br>"; listArrayRecursive($v, $ident + 1); }else{ for ($i=0; $i < $ident * 10; $i++){ echo " "; } echo $k . " : " . $v . "<br>"; } } }else{ echo "Variable = " . $array_name; } }
Usage :
$ages = array( "ahmed" => "25", "mohamed" => "35", "group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20"))); listArrayRecursive($ages);
Output will be printed array in indented way.