sarlesh
sarlesh

Reputation: 11

Warning: mysql_connect(): Error while reading greeting packet

<?php``
if(mysql_connect("localhost","root",""))
echo"connect";
else 
echo "not connect";
?>

this is my code but it's not connected . give the error as warning

Warning: mysql_connect(): MySQL server has gone away in C:..\pro1.php on line 2

Warning: mysql_connect(): Error while reading greeting packet. PID=2296 in C:..\pro1.php on line 2

Warning: mysql_connect(): MySQL server has gone away in C:..\pro1.php on line 2 not connect

Upvotes: 1

Views: 14026

Answers (3)

OmniPotens
OmniPotens

Reputation: 1125

You can try using either MySQLi or PDO and their prepared statement to be more secure.

If you intend using just MySQL then use the below code to initialize your Database connection.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

For reference see http://php.net/manual/en/function.mysql-connect.php

Alternatively kindly use MySQLi

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

For reference see http://php.net/manual/en/mysqli.construct.php

If you consider using PDO then try

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

For reference see http://php.net/manual/en/pdo.connections.php

Upvotes: 3

user3386779
user3386779

Reputation: 7185

remove '' after php open tag and try like this

  <?php
 $link = mysql_connect('localhost', 'root', '');
 if (!$link) {
 die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('dbname');   //your database name
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>

Upvotes: 0

N. Hamelink
N. Hamelink

Reputation: 603

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

http://php.net/manual/en/mysqli.construct.php

Upvotes: 1

Related Questions