How to connect to and remote database server [duplicate] - php

here i am trying to connect to MySQL database using PHP-PDO from remote server using IP address. when put ip address in place of host it gives me following error
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in D:\xampp\htdocs\oppInsights\database\Database.php on line 32
Fatal error: Uncaught exception 'Exception' with message 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. ' in D:\xampp\htdocs\oppInsights\database\Database.php:39 Stack trace: #0 D:\xampp\htdocs\oppInsights\database\Select.php(800): Database->Connection() #1 D:\xampp\htdocs\oppInsights\decision.php(19): Select->expiryContracts() #2 {main} thrown in D:\xampp\htdocs\oppInsights\database\Database.php on line 39
this is the code
<?php
class Database {
public $dbhost = "mysql:dbname=apt;host=http://10.75.225.171:3601";
public $dbuser = "tribhuvan";
public $dbpass = "123456";
public $dbname = "apt";
public $connection;
public $selectdb;
public $isConnected;
public $dbh;
//$user = 'dbuser';
//$password = 'dbpass';
public function Connection()
{
try
{
$this->dbh = new PDO($this->dbhost, $this->dbuser, $this->dbpass);
// echo "true";
return $this->dbh;
}
catch(Exception $e)
{
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function Disconnect()
{
$this->datab = null;
$this->isConnected = false;
}
}
?>
i have checked username and password they seems to be same as i gave.thank you in advance.

You need to remove http from the host and put the port number under port attribute.
Please try with this line :
$dbhost = "mysql:host=10.75.225.171;port=3601;dbname=apt";

Related

How To Handle mysql Connection Error with custom message in php using OOPS [duplicate]

This question already has an answer here:
Should we ever check for mysqli_connect() errors manually?
(1 answer)
Closed 3 years ago.
That is i write in oops it show mysql error message, that i don't want, i wan't only custom MSG.
class Myfunction{
private $DBHOST = 'localhost';
private $DBUSER = 'rot';
private $DBPASS = '';
private $DBNAME = 'database';
public $conn;
public function __construct(){
try{
$this->conn = mysqli_connect($this->DBHOST, $this->DBUSER, $this->DBPASS, $this->DBNAME);
if(!$this->conn){
throw new Exception('Connection was Not established');
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
}
}
OutPut :-
Warning: mysqli_connect(): (HY000/1045): Access denied for user
'rot'#'localhost' (using password: NO) in
C:\xampp\htdocs\CRUD-PHP\config\CUFunction.php on line 13
Message: Connection was Not Extablish
Now Question is How to remove " warning " MSG??, I want to only my custom MSG
One Possible Solution found however, i think it is not appropriate
For Example :
$this->conn = #mysqli_connect($this->DBHOST, $this->DBUSER, $this->DBPASS, $this->DBNAME);
As you said yourself, the # prefix is an error control operator. If you will be handling your own errors, you could theoretically suppress that. It is usually recommended not to suppress errors though, they are there for a reason :).
PHP.net even states
Warning
Currently the "#" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "#" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.
Be cautious while using this!
class Myfunction{
private $DBHOST = 'localhost';
private $DBUSER = 'rot';
private $DBPASS = '';
private $DBNAME = 'database';
public $conn;
public function __construct(){
try{
$this->conn = #mysqli_connect($this->DBHOST, $this->DBUSER, $this->DBPASS, $this->DBNAME);
if(!$this->conn){
throw new Exception('Connection was Not established');
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
}
}

DB connection Error In PHP Slim framework in mac Connection failed: SQLSTATE[HY000] [2002] Connection timed out

I have installed Xampp VM in mac for PHP slim framework(V3).
get an error when try to connect remote db over the internet using vpn.
error is Connection failed: SQLSTATE[HY000] [2002] Connection timed out
but xampp local db connect without any error.
I used this code for connecting.
class db
{
public $dbhost = '192.168.1.78';
public $dbuser = 'root';
public $dbpass = 'Raven898';
public $dbname = 'xyz';
public $dbport = '3306';
// Connect
public function connect()
{
$connection = 'mysql:host='.$this->dbhost.';dbname='.$this->dbname;
try {
$dbh = new PDO($connection, $this->dbuser, $this->dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: '.$e->getMessage();
}
}
}

MongoDB PHP Driver Fails to Connect and Authenticate

I have set up for the first time the authentication for MongoDB. I have two users: 'admin', (set as root in the 'admin' database) and 'testUser' which is set up as 'dbAdmin' in the 'testDatabase'.
When I use mongo shell to login using the following command everything works:
mongo -u testUser -p abcd1234 --authenticationDatabase testDatabase
On the PHP's end, I have the following code:
<?php
class DBConnection {
const HOST = '1.1.1.1';
const PORT = 27017;
const DBNAME = 'testDatabase';
const USERNAME = 'testUser';
const PASSWORD = 'abcd1234';
private static $instance;
public $connection;
public $database;
private function __construct() {
if (!extension_loaded('mongo')) die("MongoDB is not installed!");
try {
$this->connection = new MongoClient('mongodb://'.self::HOST.':'.self::PORT.'/'.self::DBNAME, array('username' => self::USERNAME, 'password' => self::PASSWORD));
$this->database = $this->connection->selectDB(self::DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
}
static public function instantiate() {
if (!isset(self::$instance)) {
$class = __CLASS__;
self:: $instance = new $class;
}
return self::$instance;
}
public function getCollection($name) {
return $this->database->selectCollection($name);
}
public function execute($code) {
return $this->database->execute($code);
}
}
?>
Naturally, host (as well as the db name, username and password) are obfuscated. I have verified multiple time that there is not a typo in the credentials. I have also verified that I can connect to the database from a remote shell, similar to how this script connects.
Still, I always get this error:
PHP Fatal error: Uncaught exception 'MongoConnectionException' with
message 'Failed to connect to: 1.1.1.1:27017: Authentication
failed on database 'testDatabase' with username 'testUser': auth failed' in
/var/www/html/wip/include/mongoConnect.php:17 Stack trace:
0 /var/www/html/wip/include/mongoConnect.php(17): MongoClient->__construct('mongodb://1.1...', Array)
1 /var/www/html/wip/include/mongoConnect.php(27): DBConnection->__construct()
2 /var/www/html/wip/migration/migrate.php(85): DBConnection::instantiate()
3 {main} thrown in /var/www/html/wip/include/mongoConnect.php on line 17
Credentials for both users are in SCRAM-SHA-1.
Any idea what is causing this connection issue?
You can try to change the way of logging in
$m = new MongoClient("mongodb://${username}:${password}#localhost");
Take a look at here:
http://php.net/manual/en/mongo.connecting.auth.php

catching a 'PDOException' when database is down

I am trying to catch an error if I cannot connect to database (eg xamp down or database connection down etc). I have tried to use PDO::errorCode() but yield no reuslts.
In my php I have a connection.php and a method ' to connect to the datatbase many times and return a new PDO instance to achieve various queries. The response displays the error message then all the php queries that call it, which also includes the name and password of the database in a non encrypted format.
How can I catch this error and replace this error message with a human readable alternative (that doesnt display the name and password)?
CONNECTION.PHP
function connect()
{
// set database server access variables:
$host = "localhost";
$user = "root";
$pass = "password";
$dbase = "dbName";
//Establish a connection
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
}
RESPONSE
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000] [2002] No connection could be made because the target
machine actively refused it. ' in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php:16
Stack trace: #0
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php(16):
PDO->__construct('mysql:host=loca...', 'root', 'password') #1
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\function\active-user.php(28):
connect() #2
D:\Users\Username\Dropbox\Web\htdocs\sitename\map-floorplan.php(10):
include('D:\Users\Username...') #3 {main} thrown in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php
on line 16
do a try/catch to catch exceptions
try{
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
} catch( PDOException $e){
$originalError = $e->getMessage();
echo 'something went wrong.. '.$originalError;
exit;
}

PDO Creation Fails when Connecting to Remote MySQL Server

My friend and I are working on a website, and I am trying to install a build of it on my machine. It is already running live on the server, I just can't seem to connect from my local machine. When I do I get the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045]
Access denied for user 'myusername'#'adsl-client.example.net' (using password: YES)' in /Users/myname/Sites/mysitefolder/req/connect.php:25
Stack trace: #0 /Users/myname/Sites/mysitefolder/req/connect.php(25): PDO->__construct('mysql:host=mysq...', 'myusername', 'mypassword')
#1 /Users/myname/Sites/burn-after-reading/inc/header.php(9): ConnectionFactory->getConnection()
#2 /Users/myname/Sites/burn-after-reading/index.php(79): include('/Users/myna...')
#3 {main} thrown in /Users/myname/Sites/mysitefolder/req/connect.php on line 25
Here is the file I am trying to connect from, connect.php
<?php
class ConnectionFactory
{
var $dbhost = 'mysql.mysitename.io';
var $dbname = 'my_database_name';
var $dbusername = 'myusername';
var $dbpassword = 'mypassword';
private static $factory;
public static function getFactory()
{
if (!self::$factory)
self::$factory = new ConnectionFactory();
return self::$factory;
}
public function getConnection()
{
$conn = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}",
$this->dbusername,
$this->dbpassword);
return $conn;
}
public function getConnectionNoName()
{
$connNoName = new PDO(
"mysql:host={$this->dbhost}",
$this->dbusername,
$this->dbpassword
);
return $connNoName;
}
}
For security reason you need to add your IP address to the list of allowed remote mysql connections.

Categories