What is the equivalent of bind_result on PDO

后端 未结 4 1962
无人共我
无人共我 2020-12-07 02:06

I\'m converting to PDO and Im using prepared statements, I want to bind my result as so $stmt->bind_result($email_count); so i am able to put this into an if

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 02:30

    For quickly retrieving a value from something like a SELECT COUNT() query, have a look at PDOStatement::fetchColumn, eg

    $stmt = $pdo->prepare('SELECT COUNT(1) FROM users WHERE email = :email');
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    $email_count = $stmt->fetchColumn();
    

    I'd also like to offer some further advice. You shouldn't be creating a PDO connection in your class constructor. This means that every time you instantiate a class extending Database, you create a new connection. Instead, pass the PDO instance as a dependency, eg

    abstract class Database {
        /**
         * @var PDO
         */
        protected $pdo;
    
        public function __construct(PDO $pdo) {
            $this->pdo = $pdo;
        }
    }
    

    The same goes for your User::insert method. Try to pass any required parameters via method arguments. If you ever want to start writing unit tests for your classes, this will be invaluable

    public function insert($email) {
        $stmt = $this->pdo->prepare('SELECT COUNT(1) FROM users WHERE email = :email');
        $stmt->bindParam(':email', $email);
        $stmt->execute();
        $email_count = $stmt->fetchColumn();
    
        // and so on
    

    And finally, for PHP only files, omit the closing PHP tag ?>. This will save you from accidentally including whitespace at the end of your files that may be sent to the browser.

提交回复
热议问题