mysql增删查改
<?php
$db_host = 'localhost:3306';
$db_user = 'root';
$db_passwd = '';
$db_name = 'test';
$conn = mysql_connect($db_host,$db_user,$db_passwd);
mysql_set_charset('utf8');//设置数据字体编码
if(!$conn){
die('Could not connect:'.mysql_error());
}
mysql_select_db($db_name);//选择连接的数据表
//查询数据库函数
function select($table,$where='',$order='',$limits='',$field=''){
$field = ($field==null)?'*':$field;
$where = ($where==null)?'':' WHERE '.$where;
$order = ($order==null)?'':' ORDER BY '.$order;
$limits = ($limits==null)?'':' LIMIT '.$limits;
$sele = 'SELECT'.$field.' FROM '.$table.$where.$order.$limits;
return mysql_query($sele);
mysql_close($conn); //关闭数据库链接
}
//插入数据库函数,第二个参数必须为数组
function insert($table,$columns){
foreach ($columns as $key => $values) {
$addkey .= '`'.$key.'`,';
if(is_numeric($values)){ //判断是不是为数字
$addvalues .= $values.',';
}else{
$addvalues .= '\''.mysql_real_escape_string($values).'\','; //转义sql语句字符
}
}
$addkey = rtrim($addkey,','); //删除字符串末尾的指定字符
$addvalues = rtrim($addvalues,',');
$inse = 'INSERT INTO '.$table.'('.$addkey.') VALUES ('.$addvalues.');';
return mysql_query($inse);
mysql_close($conn); //关闭数据库链接
}
//更新数据库函数,第二个参数必须为数组
function update($table,$data,$where){
$where = ($where==null)?'':' WHERE '.$where;
foreach ($data as $k => $v) {
if(is_numeric($v)){
$edit_data .= '`'.$k.'`'.'='.$v.',';
}else{
$edit_data .= '`'.$k.'`'.'='."'".mysql_real_escape_string($v)."',";
}
}
$edit_data = rtrim($edit_data,',');
$upda = 'UPDATE '.$table.' SET '.$edit_data.$where;
var_dump($upda);
return mysql_query($upda);
mysql_close($conn); //关闭数据库链接
}
//删除数据库数据函数
function delete($table,$where){
$where = ($where==null)?'':' WHERE '.$where;
$dele = 'DELETE FROM '.$table.$where;
return mysql_query($dele);
mysql_close($conn); //关闭数据库链接
}