我有一个 PDO 类包装器:
class DB {
private $dbh;
private $stmt;
public function __construct($user, $pass, $dbname) {
$dsn = 'mysql:host=localhost;dbname=' . $dbname;
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_PERSISTENT => true
);
try {
$this->dbh = new PDO($dsn, $user, $pass, $options);
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
return $this;
}
public function bind($pos, $value, $type = null) {
if( is_null($type) ) {
switch( true ) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($pos, $value, $type);
return $this;
}
public function execute() {
$this->stmt->execute();
}
public function resultset() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single() {
$this->execute();
return $this->stmt->fetch();
}
}
问题1: 我有以下要求:
$ids_set = implode(",", $ids); // return 2,4
$sql = 'SELECT `id`, `qty` FROM `products` WHERE `id` IN (:products_ids) ORDER BY `id`';
$arr = $this->db->query($sql)->bind(":products_ids", $ids_set)->resultset();
但是这个请求将只返回数组中的一个元素:
Array
(
[0] => Array
(
[id] => 2
[qty] => 1
)
)
但它应该返回两个元素。为什么以及如何修改我的课程?
问题2
我的类绑定函数对数据库注入安全吗?
问题 3
我有动态查询:
$sql = 'SELECT COUNT(*) FROM `orders` WHERE 1=1';
if ($filter["order"] != 0) {
$sql .= ' AND `gatewayid` = '.intval($filter["order"]).'';
}
$count = $this->db->query($sql)->single()[0];
在这种情况下如何使用我的绑定功能?谢谢!