Warning: mysql_connect(): Error while reading gree

2019-08-13 03:17发布

<?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

3条回答
Explosion°爆炸
2楼-- · 2019-08-13 03:37

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());
}
?>
查看更多
做个烂人
3楼-- · 2019-08-13 03:42
$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

查看更多
来,给爷笑一个
4楼-- · 2019-08-13 03:46

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

查看更多
登录 后发表回答