gpt4 book ai didi

php - 如何在 php 类上使用准备好的语句(命名参数)

转载 作者:行者123 更新时间:2023-12-05 06:47:00 25 4
gpt4 key购买 nike

我想知道如何在带有 pdo 类的准备好的语句中使用命名参数,因此对 pdo 的调用如下所示。

$query = $bdd->prepare('SELECT * FROM table WHERE login = :login AND pww = :pww');
$query->execute(array('login' => $login, 'pww' => $pww));

而且我想将它集成到一个类中,而不管参数的数量。

目前,我有 this代码

require_once 'constants.php';

class Mysql extends PDO {

private $con;

public function __construct() {
try {
$this->con = parent::__construct(DB_DSN, DB_USER, DB_PASS);
if ($this->getAttribute(PDO::ATTR_DRIVER_NAME) == DB_TYPE)
$this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
return $this->con;
} catch (PDOException $e) {
die('Error:' . $e->getMessage());
}
}

public function select($reqSelect) {
try {
$this->con = parent::beginTransaction();
$result = parent::prepare($reqSelect);
$result->execute();

//$this->con = parent::commit();
$this->con = parent::rollBack();
return $result;
$result->closeCursor();
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
}

public function selectAll($reqSelect) {
$result = parent::prepare($reqSelect);
$result->execute();
$resultat = $result->fetchAll();
return $resultat;
$result->closeCursor();
}
}

对于参数,我使用类似的东西(这是错误的并且容易被注入(inject))

require_once 'classes/Mysql.class.php';
$mysql = new Mysql();
$sql = 'SELECT * FROM articles WHERE id = '.$_GET['id'].' LIMIT 1';
$data = $mysql->select($sql);

谢谢。

最佳答案

看来我已经弄明白了,诀窍是向函数添加一个可选参数,只要您需要使用准备好的语句(命名参数),就可以使用它。所以函数类似于

public function selectAll($reqSelect, $param = null) {
$result = parent::prepare($reqSelect);
//Check whether the parameter was passed or not
if (is_null($param)) {
$result->execute();
$resultat = $result->fetchAll();
return $resultat;
} else {
//Binding the parameters
$result->execute($param);
$resultat = $result->fetchAll();
return $resultat;
}
$result->closeCursor();
}

应用它,就像

//First param, the SQL. Here we have named parameters, so we need them to get bind
$sql = 'SELECT * FROM articles WHERE publish = :number';
//Second param, the parameters that will get bind with the named ones
$param = array(':number' => 1);

$query = $mysql->selectAll($sql, $param);

foreach ($query as $row) {
extract($row);
echo $title . '<br />';
}

我不知道这是否被认为是最佳实践、安全甚至正确。如果我错了,请随时纠正我。

关于php - 如何在 php 类上使用准备好的语句(命名参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com