本次作业要求用PDO模板实现IMode中的四个方法,并且用参数绑定的方法防止sql注入。
<?php
$dbms='mysql';
$host='localhost';
$port='3306';
$dbName='test';
$user='root';
$pass='';
$dsn="$dbms:host=$host;port=$port;dbname=$dbName";
try
{
$dbh = new PDO($dsn, $user, $pass);
echo "连接成功<br/>";
$dbh = null;
}
catch (PDOException $e)
{
die ("错误: " . $e->getMessage() . "<br/>");
}
interface iModel
{
public function select(string $statements,array $params = []);
public function update(string $statement);
public function delete(string $statement);
public function insert(string $statement);
}
class PDOmodeL implements IModel
{
protected $dbh;
public function __construct($dsn, $user, $pass)
{
$this->dbh = new PDO($dsn, $user, $pass);
}
public function select(string $statements,array $params = [])
{
$result = $this->dbh->prepare($statements);
if($params){
foreach($params as $i=>$v){
$result->bindParam($i,$v);
}
$res = $result->fetch(PDO::FETCH_ASSOC);
var_dump($res);
}
$count= $result->execute();
return $count;
}
public function update(string $statements,array $params = [])
{
$result = $this->dbh->prepare($statements);
if($params){
foreach($params as $i=>$v){
$result->bindParam($i,$v);
}
}
$count= $result->execute();
return $count;
}
public function delete(string $statements,array $params = [])
{
$result = $this->dbh->prepare($statements);
if($params){
foreach($params as $i=>$v){
$result->bindParam($i,$v);
}
}
$count= $result->execute();
return $count;
}
public function insert(string $statements,array $params = [])
{
$result = $this->dbh->prepare($statements);
if($params){
foreach($params as $i=>$v){
$result->bindParam($i,$v);
}
}
$count= $result->execute();
return $count;
}
}
?>
网友评论