Tag Archives: query

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