note 35714 added to function.mysql-query

From: Date: Thu, 11 Sep 2003 22:00:21 +0000
Subject: note 35714 added to function.mysql-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-56279@lists.php.net to get a copy of this message
Handy array insertion query function for mysql useful for one-dimensional arrays. The code below unsets all empty array keys and does a pconnect. Declare $sql_host, $sql_user and $sql_pass before using. <?php function mysql_insert_array($db, $tbl, $arr){ global $sql_host, $sql_user, $sql_pass; $str_sql_left = "INSERT INTO " . $tbl . " ("; $str_sql_mid = ") VALUES ("; $str_sql_right = ")"; foreach ($arr as $key => $elem){ if (empty($elem)) unset($arr[$key]); } end($arr); $last_key=key($arr); $last_value = current($arr); foreach ($arr as $key => $elem) { $str_sql_left .= $key; $str_sql_mid .= "'" . $elem . "'"; if ($key!=$last_key){ $str_sql_left .= ", "; $str_sql_mid .= ", "; } } mysql_pconnect($sql_host, $sql_user, $sql_pass) or die("cant connect: " . mysql_error()); mysql_select_db($db) or die("cant use $db: " . mysql_error()); $str_sql_q = $str_sql_left . $str_sql_mid . $str_sql_right; //print "<br>" . $str_sql_q . "<br>"; mysql_query($str_sql_q) or die("cant query: " . mysql_error()); } ?> ---- Manual Page -- http://www.php.net/manual/en/function.mysql-query.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35714 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35714&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35714&report=yes

« previous php.notes (#56279) next »