Wednesday, December 19, 2007
Generate INSERT and UPDATE mysql queries
## generate INSERT query SELECT CONCAT('INSERT INTO ',table_name,' (',GROUP_CONCAT( column_name SEPARATOR ',' ),') VALUES (',GROUP_CONCAT( "'$POST_",column_name,"'" SEPARATOR ',' ),')') AS insert_query FROM information_schema.COLUMNS WHERE table_name = 'table' AND TABLE_SCHEMA = 'database'; ## generate UPDATE query SELECT CONCAT('UPDATE ',table_name,' SET ',GROUP_CONCAT( column_name,"='$POST_",column_name,"'" SEPARATOR ',' )) AS update_query FROM information_schema.COLUMNS WHERE table_name = 'table' AND TABLE_SCHEMA = 'database';I save a lot of time using this, not even saying about the typing mistakes I usually do by writing it manually.
Results:
INSERT INTO simpletable (id,date,rating) VALUES ('$POST_id','$POST_date','$POST_rating') UPDATE simpletable SET id='$POST_id',date='$POST_date',rating='$POST_rating'