title: PHP Laravel - How to dynamically connect Via SSH to a MySQL database
body: <p>Currently I have the ability to connect to either a mysql or postgres database dynamically through a job, execute a select statement then export to an excel spreadsheet:  </p>
  
  <pre><code>  DB::purge("$connectionName");
  
      if($Driver == "mysql"){
          $charset = "utf8mb4";
      } else if($Driver == "pgsql"){
          $charset = "utf8";
      } else{
          $charset = "";
      }
  
      Config::set("database.connections.$connectionName", [
          "driver" =&gt; "$Driver",
          "port" =&gt; "$Port",
          "host" =&gt; "$Host",
          "database" =&gt; "$DBName",
          "username" =&gt; "$UserName",
          "password" =&gt; "$Password",
          'charset' =&gt; "$charset"
      ]);
  
      $query = DB::connection("$connectionName")-&gt;select($statement);
      $q_raw = $query;
  
      $rowCount = count($query);
  
      $query= json_decode( json_encode($query), true);
  
      $filename_e = $filename.'-'.$range.'-^^-'.$mytime;
  
  
      if($rowCount == 0){
  
          $pdo = DB::connection($connectionName)-&gt;getPdo();
          $select = $pdo-&gt;query($statement);
  
          $colcount = $select-&gt;columnCount();
  
          $meta = $select-&gt;getColumnMeta(0);
  
          for ($i = 0; $i &lt; $colcount; ++$i) {
              $query[] = $select-&gt;getColumnMeta($i)['name'];
          }
  
  
      }
  
      Excel::create($filename_e, function($excel) use ($query, $filename) {
  
          $excel-&gt;sheet($filename, function($sheet) use ($query){
              $sheet-&gt;fromArray($query);
          });
  
      })-&gt;store('xls', storage_path('excel/exports'));
  
      $filepath = storage_path('excel/exports').'/'.$filename_e.'.xls';
  </code></pre>
  
  <p>I need the ability to do exactly this however but via a SSH connection to a MySQL server using an uploaded SSH key etc. </p>
  
  <p>Any help appreciated.</p>