• support@answerspoint.com

how to connecting mysql database in php

46658

I am trying to connect mysql through php. But it displayed "Failed to connect to MYSQL", i am trying first time Anyone has some suggestion?

2Answer


0
PHP provides mysql_connect() function to open a database connection. This function takes Three parameters and returns a MySQL link identifier on success or FALSE on failure.
 
Parameters
server -  The host name running the database server. If not specified, then the default value will be localhost.
user − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.
passwd − The password of the user accessing the database. If not specified, then the default will be an empty password.
 
<html>
<head>
<title>Database Conection</title>
</head>
<body>
	<?php
        $dbhost = 'localhost';
        $dbuser = 'root';
        $dbpass = '';
        $conn = mysql_connect($dbhost, $dbuser, $dbpass);
        if(! $conn ) 
        {
        die('Could not connect: ' . mysql_error());
        }
        echo 'Connected successfully';
        mysql_close($conn);
    ?>
</body>
</html>

 

 
 
 
  • answered 6 years ago
  • Community  wiki

0

Use this technique for best connection programme like various connection environment

<?php
$conn_server_local='localhost';
$conn_server_lan='192.168.';
$conn_server_web='domain.com';

$con_localhost=array('host' => $conn_server_local,'username' => 'localhost_user_name','password' => 'locla_pass','database' => 'local_database');
$con_lan=array('host' => $conn_server_lan,'username' => 'lan_user','password' => 'lan_pass','database' => 'lan_database');
$con_server=array('host' => $conn_server_web,'username' => 'web_user','password' => 'web_pass','database' => 'web_database');

$server='local_host';
$server_name=$_SERVER["SERVER_NAME"];
$server_addr=$_SERVER["SERVER_ADDR"];
$remote_addr=$_SERVER["REMOTE_ADDR"];
if($server_addr!=$remote_addr)
{
    if(strpos($server_addr,'192.168'))// check for lan
    {
        $server='lan_host';
    }
    else
    {
        $server='website_host';
    }
}
if($server=='local_host')
{
    $con_root=$con_localhost;
}
else
{
    if(strpos($server_ip,'192.168'))// check for lan
    {
        $con_root=$con_lan;
    }
    else
    {
        $con_root=$con_server;
    }
}
$connect_root=mysql_connect($con_root['host'],$con_root['username'],$con_root['password']);
if(!$connect_root)
{
    echo "Error in Connection<br>".mysql_error()."<br>";
    exit;
}
$dbselect=mysql_select_db($con_root['database']);
if(!$dbselect)
{
    echo "<b>Problum in database selection<br>".mysql_error()."<br></b>";
    exit;
}
?>

 

  • answered 6 years ago
  • Sunny Solu

Your Answer

    Facebook Share        
       
  • asked 6 years ago
  • viewed 46658 times
  • active 6 years ago

Best Rated Questions