문제

I want to use a global variable and use bindValue() to assign it to a place holder so the value can be inserted into a database. The function I'm using is below

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;
}

The reason I can't just make a public variable is because data is being posted from a form to it and using public or public static is an invalid syntax. The variables that I'm using are

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

Is what I want to do even possible or am I better off finding another way to assign the values so I can insert into a database?

도움이 되었습니까?

해결책

I would start by removing the creation of the database instance to outside the function, because by the looks of it you are opening and closing lots of database connections.

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']);

Or perhaps even better have some request object and use that to inject into the method.

Not sure what you mean by global variable though, because the request variables ($_GET, $_POST, etc) are superglobals meaning they are global by default. And can be accessed from anywhere (although it isn't really best practice).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top