方式一:
class SqlTool
{
private $conn = null;
private $host = "localhost";
private $username = "root";
private $password = "254416";
function __construct()
{
$this->conn = mysql_connect($this->host, $this->username, $this->password);
if (!$this->conn)
{
die("数据库链接失败" . mysql_error());
}
//选择数据库
mysql_select_db("test") or die("数据库不存在" . mysql_error());
//设置编码
mysql_set_charset("utf8", $this->conn);
//mysql_query("set names utf8");
}
function execute_dql($sql)
{
$res = mysql_query($sql, $this->conn);
if (!$res)
{
die("数据查询失败");
} else
{
return $res;
}
}
function execute_dml($sql)
{
$res = mysql_query($sql, $this->conn);
if (!$res)
{
echo mysql_error();
return - 1;
} else
{
if (mysql_affected_rows($this->conn) > 0)
{
return 1;
} else
{
return 0;
}
}
}
}
?>
方式二:通过mysqli扩展库操作mysql
class SqlTool
{
private $host = "localhost";
private $username = "root";
private $password = "254416";
private $db = "test";
private static $mysqli = null;
function __construct()
{
//新建链接
self::$mysqli = new MySQLi($this->host, $this->username, $this->password, $this->
db);
if (self::$mysqli->connect_error)
{
die("数据库连接失败" . self::$mysqli->connect_error);
}
//设置编码
self::$mysqli->set_charset("utf8");
}
function execute_dql($sql)
{
$res = self::$mysqli->query($sql);
return $res;
}
function queryfiledname($sql)
{
$filedname = self::$mysqli->query($sql);
return $filedname;
}
function execute_dml($sql)
{
$b = self::$mysqli->query($sql);
if (!$b)
{
return - 1;
} else
{
if (self::$mysqli->affected_rows > 0)
{
return 1;
} else
{
return 0;
}
}
}
}
?>
结语:
header("Content-type: text/html;charset=utf-8");
//建立链接
$mysqli = new MySQLi("localhost", "root", "254416", "test");
$sql = "insert into user (username,password,email,address,age) values (?,?,?,?,?)";
//设置编码
$mysqli->query("SET NAMES utf8");
//数据库预处理
$mysqli_stmt = $mysqli->prepare($sql) or die("数据库预处理失败");
//绑定参数
$name = "小倩";
$password = "123";
$email = "xiaoqian@";
$address = "郑州";
$age = 20;
$mysqli_stmt->bind_param("ssssi", $name, $password, $email, $address, $age) or
die("绑定参数失败");
//执行
$b = $mysqli_stmt->execute();
if (!$b)
{
die("预处理执行失败");
}
echo "添加成功";
$mysqli_stmt->close();
?>
header("Content-type: text/html;charset=utf-8");
$mysqli = new MySQLi("localhost", "root", "254416", "test");
$mysqli->query("set names utf8");
$sql = "select * from user where id>?";
$mysqli_stmt = $mysqli->prepare($sql) or die("数据库预处理失败");
$id = 20;
$mysqli_stmt->bind_param("i", $id) or die("参数绑定失败");
$mysqli_stmt->bind_result($id, $username, $password, $email, $address, $age) or ("绑定结果集失败");
$b = $mysqli_stmt->execute();
if (!$b)
{
die("数据库预处操作理失败");
}
while ($mysqli_stmt->fetch())
{
echo "--$id--$username";
}
$mysqli_stmt->free_result();
$mysqli_stmt->close();
$mysqli->close();
?>