user1661548
user1661548

Reputation:

Error messages when connecting to database

I'm having trouble connection to the database

Here is the code I am using

$con = mysql_connect('host', 'user', 'pass');
mysql_select_db('database_name', $con);

And here is the results I get

Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in /home/heartbeat_db/heartbeatsmart.com/php/config/dbconnect.php on line 2

Warning: mysql_select_db() expects parameter 2 to be resource, boolean given in /home/heartbeat_db/heartbeatsmart.com/php/config/dbconnect.php on line 3

Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in /home/heartbeat_db/heartbeatsmart.com/php/config/dbconnect.php on line 2

Warning: mysql_select_db() expects parameter 2 to be resource, boolean given in /home/heartbeat_db/heartbeatsmart.com/php/config/dbconnect.php on line 3

Upvotes: 1

Views: 155

Answers (5)

Amir
Amir

Reputation: 4111

$con = mysql_connect('host', 'user', 'password');
if (!$con) {
    die('Not connected : ' . mysql_error());
}

$db = mysql_select_db('database_name', $con);
if (!$db) {
    die ('Can\'t use database_name : ' . mysql_error());
}

Upvotes: 0

Shivam Dhabhai
Shivam Dhabhai

Reputation: 331

try using this code

$con=mysql_connect("host","user","pass");
mysql_selectdb("database_name",$con);

Upvotes: 3

Willem
Willem

Reputation: 61

It's better to use PDO or Mysqli. I prefer PDO because it also supports other databases than mysql so you can easier migrate if necessary.

You can easily make a connection through

$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');

For more information: http://php.net/manual/en/book.pdo.php

If you want to use mysqli use:

$mysqli = new mysqli("localhost", "user", "password", "database");

Upvotes: 1

Corbin Spicer
Corbin Spicer

Reputation: 285

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .      $mysqli->connect_error;
 }
echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .      $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";
?>

Upvotes: 0

doitlikejustin
doitlikejustin

Reputation: 6353

Try using this code

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);

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

Upvotes: 0

Related Questions