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" => "root", "password" => "111111", "dbname" => "test", "charset" => "utf8" ); connect($arr); if(connect($arr)){ echo "打开数据库成功。"; }else{ echo "打开数据库失败。"; } $info=array( "name"=>$_POST[‘name‘], "email"=>$_POST[‘email‘] ); /** * 插入函数封装的第一种方法,截取字符串得到需要的键值 * @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 "插入成功"; }else{ echo "插入失败"; } /** * 插入函数封装的第二种方法,连接数组值得到需要的键和值 * @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"; }
时间: 2024-12-28 11:35:12