Function connect ($hostInfo) {$link =mysql_connect ($hostInfo [' Host '], $hostInfo [' username '], $hostInfo [' Password ']) or die ("mysql connect failed."); Mysql_set_charset ($hostInfo [' CharSet ']), mysql_select_db ($hostInfo [' dbname ']);return $link;} $arr =array ("host" = "localhost", "username" and "root", "password" = "111111", "dbname" = "test", "charset" = > "UTF8"), connect ($arr), if (Connect ($arr)) {echo "Open the database successfully. ";} else{echo "failed to open the database. ";} $info =array ("name" =>$_post[' name '], "email" =>$_post[' email '));/** * Insert the first method encapsulated by the function, intercept the string to get the required key value * @param unknown $array * @param unknown $table * @return number */function insert ($array, $table) {foreach ($array as $key = $val) {$keys. = $key . ","; $vals. = "'". $val. "',";} $keys =substr ($keys, 0, strrpos ($keys, ",")) $vals =substr ($vals, 0, strrpos ($vals, ",") ); $query = "insert into {$table} ($keys) values ({$vals})";echo $query; mysql_query ($query); return mysql_insert_id ();} if (insert ($info, $table)) {echo "Insert succeeded";} else{echo "Insert Failed";} /** * Insert function encapsulates the second method, the connection array is worth the keys and values needed * @param unknown $array * @param unknown $table * @return number */function insert ($array, $table) {$keys = Join (",", array_keys ( $array)), $vals = "'". Join ("', '", array_values ($array)). "'"; $query = "insert into {$table} ({$keys}) values ({$vals})"; mysql_query ($query); return mysql_ INSERT_ID ();} if (insert ($info, $table)) {echo "Success";} else{echo "Failed";}
Connection and insertion of database operation functions