如何在类函数bindvalue中使用全局变量


How to use global variable in class function bindvalue?

我想使用全局变量并使用bindValue()将其分配给占位符,以便将值插入到数据库中。我使用的函数在

下面
public function insertComment() {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = 'INSERT INTO comments ( name, email, commentText, articleID ) VALUES ( :name, :email, :commentText, :articleID )';
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":name", $this->name, PDO::PARAM_STR );
    $st->bindValue( ":email", $this->email, PDO::PARAM_STR );
    $st->bindValue( ":commentText", $this->commentText, PDO::PARAM_STR );
    $st->bindValue( ":articleID", $this->articleID, PDO::PARAM_INT );
    $st->execute();
    $conn = null;
}

我不能只是做一个公共变量的原因是因为数据是从一个表单发布到它,使用公共或公共静态是一个无效的语法。我使用的变量是

$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$commentText = isset($_POST['comment']) ? $_POST['comment'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';

我想做的是什么,甚至可能,还是我最好找到另一种方式来分配值,这样我就可以插入到数据库中?

我将从删除数据库实例的创建到函数外部开始,因为从它的外观来看,您正在打开和关闭大量数据库连接。

class Foo
{
    private $conn;
    public function __construct(PDO $conn)
    {
        $this->conn = $conn;
    }
    public function insertComment($name, $email, $comment, $articlId) {
        $sql = 'INSERT INTO comments ( name, email, commentText, articleID ) VALUES ( :name, :email, :commentText, :articleID )';
        $st = $this->conn->prepare ( $sql );
        $st->bindValue( ":name", $name, PDO::PARAM_STR );
        $st->bindValue( ":email", $email, PDO::PARAM_STR );
        $st->bindValue( ":commentText", $commentText, PDO::PARAM_STR );
        $st->bindValue( ":articleID", $articleID, PDO::PARAM_INT );
        $st->execute();
    }
}
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$foo = new Foo($conn);
$foo->insertComment($_POST['name'], $_POST['email'], $_POST['commentText'], $_POST['articleId']);

或者最好有一些请求对象并使用它注入到方法中。

不确定你所说的global变量是什么意思,因为请求变量($_GET, $_POST等)是超全局的,这意味着它们默认是全局的。并且可以从任何地方访问(尽管这不是真正的最佳实践)。