检查表中是否存在记录,如果存在则重定向


Check if record exists in table, if so redirect

我想看看是否有记录存在于我的表中,如果它确实我想重定向我的用户,如果不是,我想插入一个记录

我有以下内容,我唯一的问题是它在我的表中一遍又一遍地插入相同的记录,所以我的初始查询似乎不工作。

$query = "SELECT * FROM `users` WHERE oauth_uid=? and oauth_provider=?";
        $stmt  = $DBH->prepare($query);
        $stmt->execute($uid, $oauth_provider);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            # silent
        }
        if (!empty($result)) {
            # User is already present - Redirect them 
            echo 'This will redir';
        } else {
            $sql = "INSERT INTO `users` (oauth_provider, oauth_uid, username, email) VALUES (:oauth_provider,:uid,:username,:email)";
            $q = $DBH->prepare($sql);
            $q->execute(array(':oauth_provider'=>$oauth_provider,':uid'=>$uid,':username'=>$username,':email'=>$email));
            echo 'done';
        }

<?php
require 'dbconfig.php';
class User {
    function checkUser($uid, $oauth_provider, $username, $email, $twitter_otoken, $twitter_otoken_secret) 
    {
        global $DBH;
        $query = "SELECT * FROM `users` WHERE oauth_uid=? and oauth_provider=?";
        $stmt  = $DBH->prepare($query);
        $stmt->execute($uid, $oauth_provider);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            # silent
        }
        if (!empty($row)) {
            # User is already present - Redirect them 
            echo 'This will redir';
        } else {
            $sql = "INSERT INTO `users` (oauth_provider, oauth_uid, username, email) VALUES (:oauth_provider,:uid,:username,:email)";
            $q = $DBH->prepare($sql);
            $q->execute(array(':oauth_provider'=>$oauth_provider,':uid'=>$uid,':username'=>$username,':email'=>$email));
            echo 'done';
        }

    }
}
?>

旧MYSQL工作

$query = mysql_query("SELECT * FROM `users` WHERE oauth_uid = '$uid' and oauth_provider = '$oauth_provider'") or die(mysql_error());
    $result = mysql_fetch_array($query);
    if (!empty($result)) {
        # User is already present
        echo'user exists';
    }

最好使用rowCount代替…

//after $stmt->execute()...
if($stmt->rowCount() != 0) {
      //proceed
}else {
      //redirect if rowCount is equal to 0
}