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

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Divyasaleh Recent comment authors
  Subscribe  
Notify of
saleh
Guest
saleh

thanks a milion 🙂

Divya
Guest

You can do as

foreach($linkres as $col => $val){
$cols .= “,” . $col;
$values .= “,'”.$val.”‘”;
}