0

I am trying to access a database on my web host with a php file that is on the same server. When trying to load the page I get the following error: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111. I cannot find a good answer what it going wrong. Below is my php that I am using. I have my IP address of my database set as my host name.

    <?php
    $con = mysql_connect("10.123.0.209:3306","username", "password");
    if (!$con){
    die("cannot connect: " . mysql_error());
     }

    mysql_select_db("matmac78_macy", $con);
    $sql = "SELECT * FROM countries";
    $mydata = mysql_query($sql, $con);

    while ($record = mysql_fetch_array($mydata)){
    echo $record['country'] . " " . $record['population'] 
    echo"<br/>";
    }

    mysql_close($con);

    ?>

Any help would be greatly appreciated!

Matt Macy
  • 141
  • 1
  • 2
  • 13
  • 4
    please use mysqli or pdo not mysql because it's deprecated – Rahul Sharma Mar 21 '17 at 15:20
  • 4
    Possible duplicate of [Lost connection to MySQL server, system error: 111](http://stackoverflow.com/questions/8495684/lost-connection-to-mysql-server-system-error-111) – Condorcho Mar 21 '17 at 15:21
  • can you connect to the mysql server using command line? Remove ':3306' from your host. – Dimi Mar 21 '17 at 15:21
  • I tried to remove :3306 and it still isn't working. Can you please explain to me about how to go about using the command line? – Matt Macy Mar 21 '17 at 15:25
  • 1
    Maybe this can help you http://stackoverflow.com/questions/5755819/lost-connection-to-mysql-server-at-reading-initial-communication-packet-syste or http://stackoverflow.com/questions/19654311/lost-connection-to-mysql-server-at-reading-initial-communication-packet-syste – Artem Kovalov Mar 21 '17 at 15:27
  • Error 111 means "connection refused". Maybe your mysql server is down, or the mysql IP is not valid. Also could be a firewall problem. – F.Igor Mar 21 '17 at 15:31

1 Answers1

0

You should switch to using PHP's PDO connection protocol.

$username = 'username';
$password = 'password';
$dbName = 'matmac78_macy';
$host = '10.123.0.209:3306';


try {
        $this->database = new \PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password );
        $this->database->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
        $this->database->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC );
        return $this->database;
    } catch (\PDOException $e) {
        throw new \Exception( "Could not establish database connection. \n" );    #Push error message
    }