Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何合并用php编写的两个服务器代码_Php_Mysql - Fatal编程技术网

如何合并用php编写的两个服务器代码

如何合并用php编写的两个服务器代码,php,mysql,Php,Mysql,我有两个用php编写的服务器代码要合并。 第一个代码是使用mysql数据库并在数据库中激发查询并返回结果 <?php //TODO: show error off require_once("mysql.class.php"); $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "project"; $db = new MySQL($dbHost,$dbUsern

我有两个用php编写的服务器代码要合并。 第一个代码是使用mysql数据库并在数据库中激发查询并返回结果

<?php

 //TODO:  show error off

  require_once("mysql.class.php");

 $dbHost = "localhost";
 $dbUsername = "root";
 $dbPassword = "";
  $dbName = "project";


  $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 ($username == NULL || $password == NULL)   
   {
    echo FAILED;
    exit;
    }

    $out = NULL;

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

case "authenticateUser":
    // code for generating list of shares. 

    if ($port != NULL  
            && ($userId = authenticateUser($db, $username, $password, $port)) != NULL) 
    {                   

        // 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." ";


        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 

                }               
                $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 "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, $port)
{

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

$out = NULL;
if ($result = $db->query($sql))
{
    if ($row = $db->fetchObject($result))
    {
            $out = $row->Id;

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

            $db->query($sql);               


    }       
}

return $out;
}

?>
两个代码都工作正常

我试着在switch语句中做另一个例子,其中的操作是“文件共享” 那不行吗

case "filesharing":$base=$_REQUEST['image'];
        //echo $base;
        $binary=base64_decode($base);
        header('Content-Type: bitmap; charset=utf-8');
        $file = fopen('uploaded_image'.time().'.jpg', 'wb');
        fwrite($file, $binary);
        fclose($file);
        $out .= "Image upload complete!!, Please check your php file     directory……";
    break;

有人能给点建议吗?

所以你基本上有两个文件,有两个独立的功能。显而易见的解决方案是用一个函数封装每一位代码,即

function query() {
/* your database query code here */
}

function file_upload() {
/* your file upload code here */
}
。。。然后将这些函数封装在一个类中

class MyCoolClass {
    function query() {
        /* your database query code here */
    }

    function file_upload() {
        /* your file upload code here */
    }
}

面向对象编程的优点(和缺点)已经做得很彻底了,只要有一个谷歌,你无疑会发现很多精彩的东西,非常好的资源。

问题到底是什么?既然你说两个代码都工作正常,那么这里就没有问题可以回答了。你是在第二个代码中使用第一个代码的输出吗?@Ghomey我必须将这两个代码整合起来files@OMTheEternity我正在开发两个模块:文件共享和聊天应用程序。现在我想将这两个文件集成到一个php文件中。我喜欢你的想法。我是php新手。您能告诉我php如何处理http POST并根据情况调用这些方法吗?可以使用superglobal$\u POST数组从表单获取发布的数据。然后根据数据是什么,调用相关的方法。是的,但是POST和GET是显式的,而请求可能来自不同的来源@Turpachul在阅读了你的链接后,我觉得这个请求更好。等一下。。让我直说吧。。当有人向您的应用程序请求数据时,您应该使用$\u GET。当有人向您的应用程序推送(插入或更新;或删除)数据时,您应该使用$\u POST。就应用程序而言,这意味着只有服务器和mysql?
class MyCoolClass {
    function query() {
        /* your database query code here */
    }

    function file_upload() {
        /* your file upload code here */
    }
}