1. CMS首页
  2. 技术杂文

PHP操作sql数据库封装成类的方法代码

<?php<br>/*<br>数据库:<br>增,删,改,查( CURD )操作<br>C: create<br>U: update<br>R: Retrieve<br>D: delete<br>*/<br>class Mysql {<br>private $dbHost; //主机<br>private $dbUser; //用户名<br>private $dbPwd; //密码<br>private $dbName; //数据库名称<br>public function __construct( $_dbHost, $_dbUser, $_dbPwd, $_dbName ){<br>$this->dbHost = $_dbHost;<br>$this->dbUser = $_dbUser;<br>$this->dbPwd = $_dbPwd;<br>$this->dbName = $_dbName;<br>//连接数据库<br>if( $this->connect() ){<br>//成功<br>//选择数据库, 设定编码<br>$this->selectDb();<br>$this->setDbCode();<br>}else {<br>die("数据库连接失败" . mysql_error() );<br>}<br>}<br>public function selectDb(){<br>mysql_select_db( $this->dbName );<br>}<br>public function setDbCode(){<br>$this->query( "set names utf8" );<br>}<br>public function query( $sql ){<br>return mysql_query( $sql );<br>}<br>public function connect(){<br>return mysql_connect( $this->dbHost, $this->dbUser, $this->dbPwd );<br>}<br>//查询所有数据----> 用途: 分页,列表等<br>public function getAll( $sql ){<br>$res = $this->query( $sql );<br>$arr = array();<br>while( $row = mysql_fetch_assoc( $res ) ){<br>$arr[] = $row;<br>}<br>return $arr;<br>}<br>//查询某条数据: 用途: 编辑(取出一条数据)等<br>public function getRow( $sql ){<br>$res = $this->query( $sql );<br>return mysql_fetch_assoc( $res );<br>}<br>//统计<br>public function getCol( $sql ){<br>$res = $this->query( $sql );<br>$row = mysql_fetch_row( $res );<br>return $row[0];<br>}<br>//封装插入语句<br>public function add( $data, $tbName ){<br>$sql = "INSERT INTO {$tbName} (";<br>$sql .= implode(",", array_keys($data) ) . ") VALUES (" ";<br>$sql .= implode( "","", array_values( $data ) ) . "")";<br>return $this->query( $sql );<br>}<br>//更新<br>public function update( $data, $tbName, $condition ){<br>$sql = "UPDATE {$tbName} SET ";<br>foreach( $data as $k => $v ){<br>$sql .= $k . " = " . ""$v",";<br>}<br>$sql = substr( $sql, 0, -1 );<br>$sql .= " " . $condition;<br>return $this->query( $sql );<br>}<br>}<br>$mysql = new Mysql( "localhost", "root", "root", "php1215_biquge" );<br>?>

发表评论

用户名: