MySQLI预处理(面向过程风格)
<?php
class DB
{
static $host = "localhost";
static $user = "root";
static $pass = "123456";
static $dbname = "test";
static function conn()
{
$link = mysqli_connect(self::$host, self::$user, self::$pass, self::$dbname);
if (mysqli_connect_errno()) {
return null;
}
return $link;
}
/**
* 查询方法
*
* @param [string] $name
* @param [int] $age
* @return bool
*/
public function query($name, $age)
{
$link = null;
$stmt = null;
try {
$link = self::conn();
if ($link) {
$sql = "select id from users where name=? and age=?";
// 创建预编译对象
$stmt = mysqli_prepare($link, $sql);
//参数绑定->给?号赋值 这里类型和顺序要一致
//i - integer(整型)、s - string(字符串)、d - double(双精度浮点型)
mysqli_stmt_bind_param($stmt, "si", $name, $age);
// 将变量绑定到准备好的语句
mysqli_stmt_bind_result($stmt, $id);
//执行sql语句
mysqli_stmt_execute($stmt);
//如果成功地读入下一条记录,fetch()方法返回TRUE
if (mysqli_stmt_fetch($stmt)) {
return true;
}
}
} catch (Exception $e) {
echo "Message:" . $e->getMessage();
} finally {
if ($stmt != null) {
//释放与执行预处理语句生成的结果集有关的内存
mysqli_stmt_free_result($stmt);
}
if ($link != null) {
//关闭数据库连接
mysqli_close($link);
}
}
return false;
}
}
MySQLI预处理(面向对象风格)
<?php
class DB
{
static $host = "localhost";
static $user = "root";
static $pass = "123456";
static $dbname = "test";
static function conn()
{
$link = new mysqli(self::$host, self::$user, self::$pass, self::$dbname);
if ($link->connect_errno) {
return null;
}
return $link;
}
/**
* 查询方法
*
* @param [string] $name
* @param [int] $age
* @return bool
*/
public function query($name, $age)
{
$link = null;
$stmt = null;
try {
$link = self::conn();
if ($link) {
$sql = "select id from users where name=? and age=?";
// 创建预编译对象
$stmt = $link->prepare($sql);
//参数绑定->给?号赋值 这里类型和顺序要一致
//i - integer(整型)、s - string(字符串)、d - double(双精度浮点型)
$stmt->bind_param("si", $name, $age);
// 将变量绑定到准备好的语句
$stmt->bind_result($id);
//执行sql语句
$stmt->execute();
//如果成功地读入下一条记录,fetch()方法返回TRUE
if ($stmt->fetch()) {
return true;
}
}
} catch (Exception $e) {
echo "Message:" . $e->getMessage();
} finally {
if ($stmt != null) {
//释放与执行预处理语句生成的结果集有关的内存
$stmt->free_result();
}
if ($link != null) {
//关闭数据库连接
$link->close();
}
}
return false;
}
}