0

Hello guys,

I know this might seem to be a duplicate question but i am having an issue connecting to my database with PDO. I tried interchanging the server name from localhost to '127.0.0.1' but to no avail i have gained success. I am here testing and trying to create my own database for my own personal use and to get an understanding of how querying a database works, but my lack of knowledge brought me here. Can someone just point me in the right direction.

a snippet of my code is below

<?php
require_once('CONFIG.php');
session_start();


   try {
            $database_handler = new PDO('mysql:host=' . $databasehost .   'houses', 'root', '');
   }
catch (PDOException $e) {
    print "Error: " . $e->getMessage();
   }



?>

So i have my Config.php file which has

<?php
$databasehost  = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'house';

$conn = mysql_connect($databasehost , $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'house';
mysql_select_db($dbname);

 ?> 

Any help would be greatly appreciated

  • 1) You have an open try-catch block.. 2) Why do you have mysql and PDO? Just use PDO it's better 3) Take a look into the manual at the dsn string parameter: http://php.net/manual/en/pdo.construct.php – Rizier123 Dec 06 '15 at 00:34
  • oops, i forgot to add the catch. –  Dec 06 '15 at 00:38
  • "Warning: PDO::__construct() )" - is that the "real" and complete message you get? – VolkerK Dec 06 '15 at 00:38
  • `. 'houses'` what's that concatenation supposed to do? – VolkerK Dec 06 '15 at 00:40
  • @VolkerK the error i get is *Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not know" and also* *Error: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known* –  Dec 06 '15 at 00:42
  • Yes, you're passing `host=locahosthouses` to the constructor ;-) – VolkerK Dec 06 '15 at 00:44

1 Answers1

1

The format of your DSN is wrong

<?php
require_once 'CONFIG.php';
session_start();

try {
    $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $databasehost, $dbname);
    $database_handler = new PDO($dsn, $dbuser, $dbpass, array(
        PDO::ATTR_EMULATE_PREPARES=>false,
        PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
        PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
    ));
}
catch (PDOException $e) {
    print "Error: " . $e->getMessage();
}

and drop the lines

$conn = mysql_connect($databasehost , $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'house';
mysql_select_db($dbname);

from your Config.php

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • btw: I just changed the connection charset to utf-8 ....you might want to have a read of http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – VolkerK Dec 06 '15 at 00:47
  • Thank you sir for shedding light on my error.Greatly appreciate it. –  Dec 06 '15 at 00:48