2014-05-03 98 views
0

我完全是MySQL和PHP的新手,我正試圖進一步開發AndroidIM項目。 這是它是基於PHP的服務器代碼:獲取隨機用戶名

<?php 
error_reporting(0); 

require_once("mysql.class.php"); 

$dbHost = "localhost"; 
$dbUsername = "username"; 
$dbPassword = "password"; 
$dbName = "name"; 


$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName); 

// if operation is failed by unknown reason 
define("FAILED", 0); 

define("SUCCESSFUL", 1); 
// when signing up, if username is already taken, return this error 
define("SIGN_UP_USERNAME_CRASHED", 2); 
// when add new friend request, if friend is not found, return this error 
define("ADD_NEW_USERNAME_NOT_FOUND", 2); 
// TIME_INTERVAL_FOR_USER_STATUS: if last authentication time of user is older 
// than NOW - TIME_INTERVAL_FOR_USER_STATUS, then user is considered offline 
define("TIME_INTERVAL_FOR_USER_STATUS", 60); 
define("USER_APPROVED", 1); 
define("USER_UNAPPROVED", 0); 
$username = (isset($_REQUEST['username']) && count($_REQUEST['username']) > 0) 
          ? $_REQUEST['username'] 
          : NULL; 
$password = isset($_REQUEST['password']) ? md5($_REQUEST['password']) : NULL; 
$port = isset($_REQUEST['port']) ? $_REQUEST['port'] : NULL; 
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : NULL; 
if ($action == "testWebAPI") 
{ 
    if ($db->testconnection()){ 
    echo SUCCESSFUL; 
    exit; 
    }else{ 
    echo FAILED; 
    exit; 
    } 
} 

if ($username == NULL || $password == NULL) 
{ 
    echo FAILED; 
    exit; 
} 

$out = NULL; 

error_log($action."\r\n", 3, "error.log"); 
switch($action) 
{ 


    case "authenticateUser": 



     if ($userId = authenticateUser($db, $username, $password)) 
     {     

      // providerId and requestId is Id of a friend pair, 
      // providerId is the Id of making first friend request 
      // requestId is the Id of the friend approved the friend request made by providerId 

      // fetching friends, 
      // left join expression is a bit different, 
      //  it is required to fetch the friend, not the users itself 

      $sql = "select u.Id, u.username, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP, 
             f.providerId, f.requestId, f.status, u.port 
          from friends f 
          left join users u on 
             u.Id = if (f.providerId = ".$userId.", f.requestId, f.providerId) 
          where (f.providerId = ".$userId." and f.status=".USER_APPROVED.") or 
             f.requestId = ".$userId." "; 

      //$sqlmessage = "SELECT * FROM `messages` WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 "; 

      $sqlmessage = "SELECT m.id, m.fromuid, m.touid, m.sentdt, m.read, m.readdt, m.messagetext, u.username from messages m \n" 
    . "left join users u on u.Id = m.fromuid WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 "; 


      if ($result = $db->query($sql))   
      { 
        $out .= "<data>"; 
        $out .= "<user userKey='".$userId."' />"; 
        while ($row = $db->fetchObject($result)) 
        { 
         $status = "offline"; 
         if (((int)$row->status) == USER_UNAPPROVED) 
         { 
          $status = "unApproved"; 
         } 
         else if (((int)$row->authenticateTimeDifference) < TIME_INTERVAL_FOR_USER_STATUS) 
         { 
          $status = "online"; 

         } 
         $out .= "<friend username = '".$row->username."' status='".$status."' IP='".$row->IP."' userKey = '".$row->Id."' port='".$row->port."'/>"; 

               // to increase security, we need to change userKey periodically and pay more attention 
               // receiving message and sending message 

        } 
         if ($resultmessage = $db->query($sqlmessage))   
          { 
          while ($rowmessage = $db->fetchObject($resultmessage)) 
           { 
           $out .= "<message from='".$rowmessage->username."' sendt='".$rowmessage->sentdt."' text='".$rowmessage->messagetext."' />"; 
           $sqlendmsg = "UPDATE `messages` SET `read` = 1, `readdt` = '".DATE("Y-m-d H:i")."' WHERE `messages`.`id` = ".$rowmessage->id.";"; 
           $db->query($sqlendmsg); 
           } 
          } 
        $out .= "</data>"; 
      } 
      else 
      { 
       $out = FAILED; 
      }   
     } 
     else 
     { 
       // exit application if not authenticated user 
       $out = FAILED; 
     } 



    break; 

    case "signUpUser": 
     if (isset($_REQUEST['email'])) 
     { 
      $email = $_REQUEST['email'];  

      $sql = "select Id from users 
          where username = '".$username."' limit 1"; 



      if ($result = $db->query($sql)) 
      { 
        if ($db->numRows($result) == 0) 
        { 
          $sql = "insert into users(username, password, email) 
           values ('".$username."', '".$password."', '".$email."') ";       

           error_log("$sql", 3 , "error_log"); 
          if ($db->query($sql)) 
          { 
            $out = SUCCESSFUL; 
          }    
          else { 
            $out = FAILED; 
          }       
        } 
        else 
        { 
         $out = SIGN_UP_USERNAME_CRASHED; 
        } 
      }      
     } 
     else 
     { 
      $out = FAILED; 
     } 
    break; 

    case "sendMessage": 
    if ($userId = authenticateUser($db, $username, $password)) 
     { 
     if (isset($_REQUEST['to'])) 
     { 
      $tousername = $_REQUEST['to']; 
      $message = $_REQUEST['message']; 

      $sqlto = "select Id from users where username = '".$tousername."' limit 1"; 



        if ($resultto = $db->query($sqlto))   
        { 
         while ($rowto = $db->fetchObject($resultto)) 
         { 
          $uto = $rowto->Id; 
         } 
         $sql22 = "INSERT INTO `messages` (`fromuid`, `touid`, `sentdt`, `messagetext`) VALUES ('".$userId."', '".$uto."', '".DATE("Y-m-d H:i")."', '".$message."');";      

           error_log("$sql22", 3 , "error_log"); 
          if ($db->query($sql22)) 
          { 
            $out = SUCCESSFUL; 
          }    
          else { 
            $out = FAILED; 
          }      
         $resultto = NULL; 
        } 

     $sqlto = NULL; 
     } 
     } 
     else 
     { 
      $out = FAILED; 
     } 
    break; 

    case "addNewFriend": 
     $userId = authenticateUser($db, $username, $password); 
     if ($userId != NULL) 
     { 

      if (isset($_REQUEST['friendUserName']))   
      {    
       $friendUserName = $_REQUEST['friendUserName']; 

       $sql = "select Id from users 
           where username='".$friendUserName."' 
           limit 1"; 
       if ($result = $db->query($sql)) 
       { 
         if ($row = $db->fetchObject($result)) 
         { 
          $requestId = $row->Id; 

          if ($row->Id != $userId) 
          { 
            $sql = "insert into friends(providerId, requestId, status) 
             values(".$userId.", ".$requestId.", ".USER_UNAPPROVED.")"; 

            if ($db->query($sql)) 
            { 
              $out = SUCCESSFUL; 
            } 
            else 
            { 
              $out = FAILED; 
            } 
          } 
          else 
          { 
           $out = FAILED; // user add itself as a friend 
          }             
         } 
         else 
         { 
          $out = FAILED;      
         } 
       }        
       else 
       { 
         $out = FAILED; 
       }    
      } 
      else 
      { 
        $out = FAILED; 
      }   
     } 
     else 
     { 
      $out = FAILED; 
     } 
    break; 

    case "responseOfFriendReqs": 
     $userId = authenticateUser($db, $username, $password); 
     if ($userId != NULL) 
     { 
      $sqlApprove = NULL; 
      $sqlDiscard = NULL; 
      if (isset($_REQUEST['approvedFriends'])) 
      { 
        $friendNames = split(",", $_REQUEST['approvedFriends']); 
        $friendCount = count($friendNames); 
        $friendNamesQueryPart = NULL; 
        for ($i = 0; $i < $friendCount; $i++) 
        { 
        if (strlen($friendNames[$i]) > 0) 
        { 
         if ($i > 0) 
         { 
          $friendNamesQueryPart .= ","; 
         } 

         $friendNamesQueryPart .= "'".$friendNames[$i]."'"; 

        }    

        } 
        if ($friendNamesQueryPart != NULL) 
        { 
        $sqlApprove = "update friends set status = ".USER_APPROVED." 
            where requestId = ".$userId." and 
               providerId in (select Id from users where username in (".$friendNamesQueryPart.")); 
           ";  
        } 

      } 
      if (isset($_REQUEST['discardedFriends'])) 
      { 
        $friendNames = split(",", $_REQUEST['discardedFriends']); 
        $friendCount = count($friendNames); 
        $friendNamesQueryPart = NULL; 
        for ($i = 0; $i < $friendCount; $i++) 
        { 
        if (strlen($friendNames[$i]) > 0) 
        { 
         if ($i > 0) 
         { 
          $friendNamesQueryPart .= ","; 
         } 

         $friendNamesQueryPart .= "'".$friendNames[$i]."'"; 

        }     
        } 
        if ($friendNamesQueryPart != NULL) 
        { 
        $sqlDiscard = "delete from friends 
             where requestId = ".$userId." and 
                providerId in (select Id from users where username in (".$friendNamesQueryPart.")); 
              "; 
        }      
      } 
      if ( ($sqlApprove != NULL ? $db->query($sqlApprove) : true) && 
         ($sqlDiscard != NULL ? $db->query($sqlDiscard) : true) 
       ) 
      { 
       $out = SUCCESSFUL; 
      } 
      else 
      { 
       $out = FAILED; 
      }  
     } 
     else 
     { 
      $out = FAILED; 
     } 
    break; 

    default: 
     $out = FAILED;  
     break; 
} 

echo $out; 



/////////////////////////////////////////////////////////////// 
function authenticateUser($db, $username, $password) 
{ 

    $sql22 = "select * from users 
        where username = '".$username."' and password = '".$password."' 
        limit 1"; 

    $out = NULL; 
    if ($result22 = $db->query($sql22)) 
    { 
     if ($row22 = $db->fetchObject($result22)) 
     { 
       $out = $row22->Id; 

       $sql22 = "update users set authenticationTime = NOW(), 
                   IP = '".$_SERVER["REMOTE_ADDR"]."' , 
                   port = 15145 
           where Id = ".$row22->Id." 
           limit 1"; 

       $db->query($sql22);    


     }  
    } 

    return $out; 
} 

?> 

現在我要選擇從我的數據庫隨機用戶。 我知道如何做應用程序部分,但正如我已經說過,我不知道如何做服務器部分。 請問有人能告訴我如何做到這一點?

+1

有多種方式可以使用「隨機」。在PHP中,或在SQL中。 PHP會是'mt_rand()'或'uniqid()'或其他一些確定的,而SQL就是'RAND()'ORDER BY ORDER BY RAND()'---你得到它的基本要點。 –

+0

我也注意到您正在使用MD5進行密碼存儲。我建議你不要使用它。這是舊的,並認爲太「快」。使用[** CRYPT_BLOWFISH **](http://security.stackexchange.com/q/36471)或PHP 5.5的['password_hash()'](http://www.php.net/manual/en/) function.password-hash.php)函數。對於PHP <5.5,使用['password_hash()兼容包]](https://github.com/ircmaxell/password_compat)。 –

+1

這是真的,因爲線'現在我想添加一個函數給應用程序一個隨機的用戶名',所以被問到的內容令人困惑。我想你也應該學習如何很好地格式化英語句子。 – Rahul

回答

2

試試這個:

SELECT username 
FROM users 
ORDER BY RAND() 
LIMIT 1 

該查詢會隨機從users表中選擇一個username

編輯:

如果表中包含成千上萬的記錄,RAND()不會是一個好主意。因此,另一種替代方法是:

  1. 使用MAX(userid)查找用戶名最大的用戶名。

  2. 選擇一個小於php中最大的id的隨機數。

  3. 用隨機數查詢記錄。像:

    SELECT username 
    FROM users 
    WHERE userid='$randnum' 
    

,因爲它是對查詢的恆定值,此方法會更快。

+0

因此,這:'案 「randomUser」: \t \t如果(isset($ _ REQUEST [ '隨機'])) \t \t { \t \t \t $隨機= $ _REQUEST [ '隨機']; \t \t \t \t $ SQL = 「SELECT用戶名來自用戶的 \t \t \t \t \t ORDER BY RAND() \t \t \t \t \t \t LIMIT 1」; \t \t \t如果($導致= $ DB->查詢($ SQL))\t \t \t \t \t \t { \t \t \t $出= 「」。 \t \t \t $ out。=「」; \t \t \t而($ rowrandom = $ DB-> fetchObject($結果)) \t \t \t \t \t { \t \t \t \t \t $出。= 「<朋友的用戶名=「」。$行向>用戶名。 「'/>」; \t \t \t \t \t} \t \t \t $出= 「」。 \t \t \t \t \t \t} \t \t \t}'會正常工作? – user3557747

+3

@ user3557747:爲什麼不只是測試它? –

+2

@ user3557747那......那不是如何使用評論。就像**一樣**。 – Dan

-1

這會給你一個隨機的5位數的字符串。您可以通過更改此場景中的最後一位數字(5)來修改長度。

$RandNumber = substr(md5(rand()), 0, 5); 
+1

旁註:'mt_rand()'是比'蘭特()' –

+1

快,但我並不需要一個完全隨機的字符串,我需要它已經存在於表中的用戶名。 – user3557747

+0

那你應該這麼說。你寫了'現在我想添加一個函數給應用程序一個隨機的用戶名。 」。不是我想從我的數據庫中選擇一個隨機用戶。在那種情況下,你需要@Raging Bull的答案。 –