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

时间:2013-05-22 18:29:12

标签: php mysql pdo

我试图查看我的表中是否存在记录,如果它确实想重定向我的用户,如果没有,则id就像插入记录一样。

我有以下内容,我唯一的问题是它在我的表中反复插入相同的记录,所以我的初始查询似乎无法正常工作。

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

1 个答案:

答案 0 :(得分:1)

如果你可以使用rowCount而不是那个......那就更好了。

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