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).