Return to Snippet

Revision: 58405
at July 13, 2012 02:39 by lemcoe9


Initial Code
function get_insert_query($table, $array) {
	$insert_text = "INSERT INTO " . $table;
	$keys = array();
	$values = array();
	foreach ($array as $k=>$v) {
		$keys[] = $k;
		$values[] = $v;
	}
	$key_string = "(";
	foreach ($keys as $key) {
		$key_string = $key_string . $key . ", ";
	}
	$key_string = substr($key_string, 0, -2);
	$insert_text = $insert_text . " " . $key_string . ")";;
	$insert_text = $insert_text . " VALUES ";
	$value_string = "(";
	foreach ($values as $value) {
		if (gettype($value) == "string") {
			$value_string = $value_string . "'" . $value . "', ";
		}
		else {
			$value_string = $value_string . $value . ", ";
		}
	}
	$value_string = substr($value_string, 0, -2);
	$insert_text = $insert_text . $value_string . ")";
	return $insert_text;
}

$data = array('id' => 23, 'name' => 'David Lemcoe', 'address' => '123 Green St.');
echo get_insert_query("users", $data);
## Echos: INSERT INTO users (id, name, address) VALUES (23, 'David Lemcoe', '123 Green St.')

Initial URL
http://blog.lemcoe.com/?p=61

Initial Description
Takes your table name and key=>value array of values and returns the text for inserting into a MySQL database. Automatically surrounds strings with single quotes.

Initial Title
MySQL INSERT Query Generator w/ Strings

Initial Tags
mysql, text, query

Initial Language
PHP