数据库操作函数之连接和插入
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"; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。