title: Can't establish a connection between PHP and MySQL
body: <p>I am creating a database for a chat application to store users, friends and messages. I have a MySQL database stored into an online server. I also have two PHP files. One index file and another file which contains a class that it is used in the index file.</p>
  
  <p>mysql.class.php</p>
  
  <pre><code>    &lt;?php
  
  
  class MySQL
  {   
      private $dbLink;
      private $dbHost;
      private $dbUsername;
      private $dbPassword;
      private $dbName;
      public  $queryCount;
  
      function MySQL($dbHost,$dbUsername,$dbPassword,$dbName)
      {
          $this-&gt;dbHost = $dbHost;
          $this-&gt;dbUsername = $dbUsername;
          $this-&gt;dbPassword = $dbPassword;
          $this-&gt;dbName = $dbName;    
          $this-&gt;queryCount = 0;      
      }
      function __destruct()
      {
          $this-&gt;close();
      }
      //connect to database
      private function connect() {    
          $this-&gt;dbLink = mysql_connect($this-&gt;dbHost, $this-&gt;dbUsername, $this-&gt;dbPassword);     
          if (!$this-&gt;dbLink) {           
              $this-&gt;ShowError();
              return false;
          }else if ($this-&gt;dbLink){
              echo 'Success!';
          }
          else if (!mysql_select_db($this-&gt;dbName,$this-&gt;dbLink)) {
              $this-&gt;ShowError();
              return false;
          }
          else {
              mysql_query("set names latin5",$this-&gt;dbLink);
              return true;
          }
          unset ($this-&gt;dbHost, $this-&gt;dbUsername, $this-&gt;dbPassword, $this-&gt;dbName);     
      }   
      /*****************************
       * Method to close connection *
       *****************************/
      function close()
      {
          @mysql_close($this-&gt;dbLink);
      }
      /*******************************************
       * Checks for MySQL Errors
       * If error exists show it and return false
       * else return true  
       *******************************************/
      function ShowError()
      {
          $error = mysql_error();
          //echo $error;      
      }   
      /****************************
       * Method to run SQL queries
       ****************************/
      function  query($sql)
      {   
          if (!$this-&gt;dbLink) 
              $this-&gt;connect();
  
          if (! $result = mysql_query($sql,$this-&gt;dbLink)) {
              $this-&gt;ShowError();         
              return false;
          }
          $this-&gt;queryCount++;    
          return $result;
      }
      /************************
      * Method to fetch values*
      *************************/
      function fetchObject($result)
      {
          if (!$Object=mysql_fetch_object($result))
          {
              $this-&gt;ShowError();
              return false;
          }
          else
          {
              return $Object;
          }
      }
      /*************************
      * Method to number of rows
      **************************/
      function numRows($result)
      {
          if (false === ($num = mysql_num_rows($result))) {
              $this-&gt;ShowError();
              return -1;
          }
          return $num;        
      }
      /*******************************
       * Method to safely escape strings
       *********************************/
      function escapeString($string)
      {
          if (get_magic_quotes_gpc()) 
          {
              return $string;
          } 
          else 
          {
              $string = mysql_escape_string($string);
              return $string;
          }
      }
  
      function free($result)
      {
          if (mysql_free_result($result)) {
              $this-&gt;ShowError();
              return false;
          }   
          return true;
      }
  
      function lastInsertId()
      {
          return mysql_insert_id($this-&gt;dbLink);
      }
  
      function getUniqueField($sql)
      {
          $row = mysql_fetch_row($this-&gt;query($sql));
  
          return $row[0];
      }
      function testconnection() { 
          $this-&gt;dbLink = mysql_connect($this-&gt;dbHost, $this-&gt;dbUsername, $this-&gt;dbPassword);     
          if (!$this-&gt;dbLink) {           
              $this-&gt;ShowError();
              return false;
          }
          else if (!mysql_select_db($this-&gt;dbName,$this-&gt;dbLink)) {
              $this-&gt;ShowError();
              return false;
          }
          else {
              mysql_query("set names latin5",$this-&gt;dbLink);
              return true;
          }
          unset ($this-&gt;dbHost, $this-&gt;dbUsername, $this-&gt;dbPassword, $this-&gt;dbName);     
      }       
  }
  </code></pre>
  
  <p>index.php</p>
  
  <pre><code>&lt;?php
  
  
  require_once("mysql.class.php");
  
  
  
  $dbHost = "host";
  $dbUsername = "root";
  $dbPassword = "";
  $dbName = "db 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']) &amp;&amp; count($_REQUEST['username']) &gt; 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-&gt;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-&gt;query($sql))         
              {
                      $out .= "&lt;data&gt;"; 
                      $out .= "&lt;user userKey='".$userId."' /&gt;";
                      while ($row = $db-&gt;fetchObject($result))
                      {
                          $status = "offline";
                          if (((int)$row-&gt;status) == USER_UNAPPROVED)
                          {
                              $status = "unApproved";
                          }
                          else if (((int)$row-&gt;authenticateTimeDifference) &lt; TIME_INTERVAL_FOR_USER_STATUS)
                          {
                              $status = "online";
  
                          }
                          $out .= "&lt;friend  username = '".$row-&gt;username."'  status='".$status."' IP='".$row-&gt;IP."' userKey = '".$row-&gt;Id."'  port='".$row-&gt;port."'/&gt;";
  
                                                  // to increase security, we need to change userKey periodically and pay more attention
                                                  // receiving message and sending message 
  
                      }
                          if ($resultmessage = $db-&gt;query($sqlmessage))           
                              {
                              while ($rowmessage = $db-&gt;fetchObject($resultmessage))
                                  {
                                  $out .= "&lt;message  from='".$rowmessage-&gt;username."'  sendt='".$rowmessage-&gt;sentdt."' text='".$rowmessage-&gt;messagetext."' /&gt;";
                                  $sqlendmsg = "UPDATE `messages` SET `read` = 1, `readdt` = '".DATE("Y-m-d H:i")."' WHERE `messages`.`id` = ".$rowmessage-&gt;id.";";
                                  $db-&gt;query($sqlendmsg);
                                  }
                              }
                      $out .= "&lt;/data&gt;";
              }
              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-&gt;query($sql))
               {
                      if ($db-&gt;numRows($result) == 0) 
                      {
                              $sql = "insert into users(username, password, email)
                                  values ('".$username."', '".$password."', '".$email."') ";                          
  
                                  error_log("$sql", 3 , "error_log");
                              if ($db-&gt;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-&gt;query($sqlto))         
                      {
                          while ($rowto = $db-&gt;fetchObject($resultto))
                          {
                              $uto = $rowto-&gt;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-&gt;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-&gt;query($sql))
                   {
                          if ($row = $db-&gt;fetchObject($result))
                          {
                               $requestId = $row-&gt;Id;
  
                               if ($row-&gt;Id != $userId)
                               {
                                       $sql = "insert into friends(providerId, requestId, status)
                                           values(".$userId.", ".$requestId.", ".USER_UNAPPROVED.")";
  
                                       if ($db-&gt;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 &lt; $friendCount; $i++)
                    {
                      if (strlen($friendNames[$i]) &gt; 0)
                      {
                          if ($i &gt; 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 &lt; $friendCount; $i++)
                    {
                      if (strlen($friendNames[$i]) &gt; 0)
                      {
                          if ($i &gt; 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-&gt;query($sqlApprove) : true) &amp;&amp;
                          ($sqlDiscard != NULL ? $db-&gt;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-&gt;query($sql22))
      {
          if ($row22 = $db-&gt;fetchObject($result22))
          {
                  $out = $row22-&gt;Id;
  
                  $sql22 = "update users set authenticationTime = NOW(), 
                                                                   IP = '".$_SERVER["REMOTE_ADDR"]."' ,
                                                                   port = 15145 
                                  where Id = ".$row22-&gt;Id."
                                  limit 1";
  
                  $db-&gt;query($sql22);             
  
  
          }       
      }
  
      return $out;
  }
  
  ?&gt;
  </code></pre>
  
  <p>The first four variables in index.php must be changed depending on my MySQL server configuration. But still I can't establish a connection between the PHP and the database. Is there something wrong with one of the PHP files?</p>