<?php //创建一个名为mysqld的数据库类 class mysql { /** *定义一个连接服务器和数据库的方法 * @param string $ip ='localhost'服务器地址(设置默认为本机localhost) * @param string $user 数据库账户名 * @param string $pwd 数据库账号密码 * @param string $dbname 数据库名 * @param 编码格式 $code ="utf8"(默认为“utf8”) */ public function __construct($ip = 'localhost', $user, $pwd, $dbname, $code = 'utf8') { @mysql_connect($this->ip, $user, $pwd) or die('服务器连接失败'); @mysql_select_db($dbname) or die('连接数据库失败'); mysql_query("set names " . $code); } /** *定义一个查询数据库数据的方法 * @param string $sql 查询数据库的SQL语句 */ public function query($sql) { return mysql_query($sql); //函数执行一条 MySQL 查询 } /** *定义一条返回数据库单条记录的方法 * @param string $sql 查询数据库的SQL语句 */ public function get_one($sql) { $result = $this->query($sql); $info = array(); $info = mysql_fetch_assoc($result); //从结果集中取得一行作为关联数组 return $info; } /** *定义一个返回数据库数据表所有记录的方法 * @param string $sql 查询数据库的SQL语句 */ public function get_list($sql) { $result = $this->query($sql); $list = array(); while ($row = mysql_fetch_assoc($result)) { $list[] = $row; } return $list; } /** *定义一个删除数据库记录的方法 * @param string $table 数据表名称 * @param string $where 条件语句(默认条件为空) */ public function mysql_delete($table, $where = '') { $sql = 'delete from ' . $table; if ($where != '') { $sql .= ' where ' . $where; } $result = $this->query($sql); return $result; } /** *定义一个更新(修改)数据库某个数据记录的方法 * @param string $table 数据表名称 * @param array $data 要更新的记录(存到关联数组中) * @param string $where 条件语句 */ public function mysql_update($table, $data, $where) { $sql = 'update ' . $table . ' set '; $set = ''; foreach ($data as $key => $value) { $set .= '`' . $key . '`' . '="' . $value . '",'; } //用rtrim方法移除$set字符串右侧的',',保证SQL语句不会出错 $set = rtrim($set, ','); $sql .= $set; if ($where != '') { $sql .= ' where ' . $where; } $result = $this->query($sql); return $result; } /** *定义一个插入一条记录到数据库某数据表的方法 * @param string $table 要插入的数据表 * @param string $data 要插入的数据(数组形式) */ public function insert($table, $data) { $key = array_keys($data); //函数返回包含数组中所有键名的一个新数组 $key = implode('`,`', $key); //返回由数组元素组合成的字符串 $value = array_values($data); //函数返回数组的所有值(非键名) $value = '"' . implode('","', $value) . '"'; //返回由数组元素组合成的字符串 $sql = 'insert into ' . $table . '(`' . $key . '`)values(' . $value . ')'; $result = $this->query($sql); return $result; } }
转载于:https://my.oschina.net/arin/blog/646215