本次作業(yè)要求用PDO模板實現(xiàn)IMode中的四個方法延刘,并且用參數(shù)綁定的方法防止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;
}
}
?>