I like drupal's db_query solution, it's simple, it's secure and easy to implement. If you want to use it outside of the Drupal framework, here is a stand alone code for mysql...
function _db_query_callback($match,$init=FALSE){
static $args=NULL;if($init){$args=$match;return;}switch($match[1]){case'%d':// We must use type casting to int to convert FALSE/NULL/(TRUE?)return(int)array_shift($args);// We don't need db_escape_string as numbers are db-safecase'%s':returnmysql_escape_string(array_shift($args));case'%%':return'%';case'%f':return(float)array_shift($args);case'%b':// binary datareturn"'".mysql_real_escape_string(array_shift($args))."'";}}function db_query($query){$args=func_get_args();array_shift($args);if(isset($args[0]) and is_array($args[0])){// 'All arguments in one array' syntax$args=$args[0];}
_db_query_callback($args,TRUE);$query=preg_replace_callback('/(%d|%s|%%|%f|%b)/','_db_query_callback',$query);returnmysql_query($query);}
Firts you need to connect to the database, then you can use the function like this:
$conn=mysql_connect([HOST],[USERNAME],[PASSWORD]) or die(mysql_error());;mysql_select_db([DB_NAME]) or die(mysql_error());
db_query('INSERT INTO `demo_table` (name,address,number) VALUES("%s","%s",%d)','name','address',123);