<?php
class Mysql{
// 数据库配置信息
private $host;
private $port;
private $user;
private $pass;
private $dbName;
private $charset;
// 数据库连接
private $conn;
// 构造函数
public function __construct($host, $port, $user, $pass, $dbName, $charset)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->dbName = $dbName;
$this->charset = $charset;
// 连接数据库
$this->connect();
}
// 连接数据库
private function connect()
{
$this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dbName, $this->port);
if ($this->conn->connect_error) {
die('Connect Error (' . $this->conn->connect_errno . ') ' . $this->conn->connect_error);
}
$this->conn->set_charset($this->charset);
}
// 查询
public function query($sql)
{
$res = $this->conn->query($sql);
return $res;
}
// 获取一行
public function getRow($sql)
{
$res = $this->query($sql);
if ($res && $res->num_rows > 0) {
return $res->fetch_assoc();
}
return false;
}
// 获取多行
public function getRows($sql)
{
$res = $this->query($sql);
if ($res && $res->num_rows > 0) {
$rows = array();
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
return false;
}
// 执行语句
public function exec($sql)
{
$res = $this->conn->query($sql);
if ($res) {
return $this->conn->affected_rows;
}
return false;
}
}
// 使用实例
$mysql = new Mysql('localhost', 3306, 'root', 'root', 'test', 'utf8');
$sql = 'select * from user where id = 1';
$row = $mysql->getRow($sql);
print_r($row);
$sql = 'update user set name = "test" where id = 1';
$res = $mysql->exec($sql);
echo $res;