[wp-hackers] Better insert and update

Matt Mullenweg m at mullenweg.com
Mon May 15 16:14:48 GMT 2006


function insert($tbl, $hash){
	$fields = array_keys($hash);
	$this->query("INSERT INTO $tbl (`".implode('`,`',$fields)."`) VALUES 
	return $this->insert_id;

function update($tbl, $hash, $where){
	$bits = array();
	foreach( array_keys($hash) as $k )
		$bits[] = "`$k`='$hash[$k]'";
	return $this->query("UPDATE $tbl SET ".implode(', ',$bits)." WHERE 

In the $wpdb object. We could also move all escaping to this level, but 
that's a separate issue.

It's a bit of code I got from Flickr Cal on something we collaborated 
on, I've been using it in another project and it feels clean.

$wpdb->insert( 'table', array( 'this' => 'that', 'and => 'another' ) );

$wpdb->update( $wpdb->posts, array( 'comment_count' => 0 ), "ID = $id");

Matt Mullenweg
  http://photomatt.net | http://wordpress.org
http://automattic.com | http://akismet.com

More information about the wp-hackers mailing list