conn->prepare($sql); $s"/>

Mysql查询的几种方式样例(PDO)

Published
July 29, 2022
浏览次数 :  3

SELECT

$sql = "SELECT email FROM users WHERE email = :email";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute([':email' => $email]);

查询结果验证方式: $stmt->rowCount() 如果有结果就是大于0, 如果没结果就是等于0 。

INSERT

$sql = "INSERT INTO users (name,email,password) VALUES (:name,:email,:pass)";

    $stmt = $this->conn->prepare($sql);
    $stmt->execute([':name' => $name,':email' => $email,':pass' => $password]);

这个结果,也就是 $result = $stmt->execute([‘:name’ => $name,’:email’ => $email,’:pass’ => $password]); 返回的是true或者false, 成功是true, 错误是false.

UPDATE

$sql = "UPDATE users SET token = :token,token_expire = DATE_ADD(NOW(),INTERVAL 10 MINUTE) WHERE email = :email";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute(['token' => $token,'email' => $email]);

这个结果也是返回的boolean,成功是true, 错误是false. 也可以利用函数来获取结果。

public function forgot_password($token,$email) {
    $sql = "UPDATE users SET token = :token,token_expire = DATE_ADD(NOW(),INTERVAL 10 MINUTE) WHERE email = :email";
    $stmt = $this->conn->prepare($sql);
    $stmt->execute(['token' => $token,'email' => $email]);

    return true;

  }

DELETE

//DELETE BOOK FROM DATABASE
    
    $sql = "DELETE FROM books WHERE id=?";
    $stmt = $conn->prepare($sql);
    $res = $stmt->execute([$bookId]);

delete动作返回的结果也是Boolean, 删除成果是return true, 没有成功是return false .


Top