1

Im trying to see if a record exists in my table, if it does id like to redirect my user, if not, id like to insert a record.

I have the following, my only problem is its inserting the same record over and over in my table, so my initial query doesnt seem to be working.

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

Complete

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


    }
}
?>

Old MYSQL Worked

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

1 回答 1

1

如果您可以使用 rowCount 而不是那个更好...

//after $stmt->execute()...
if($stmt->rowCount() != 0) {
      //proceed
}else {
      //redirect if rowCount is equal to 0
}
于 2013-06-25T00:38:02.710 回答