ddesai
ddesai

Reputation: 519

Error Connecting to Database via PHP

I am trying to connect to my database via PHP but get blank page when I run through Safari(http://pushchat.local:11111/test/databasename.php)

I can see my datbasename.php file under http://pushchat.local:11111/test/ as shown below: enter image description here

Following is my PHP code:

try
{
    if (!defined('APPLICATION_ENV'))
        define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : ‘development’);

    require_once '../api_config.php';
    $config = $config[APPLICATION_ENV];

    $pdo = new PDO(
        'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], 
        $config['db']['username'], 
        $config['db']['password'],
        array());

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->query('SET NAMES utf8');

    echo 'Database connection successful!';
}
catch (Exception $e)
{
    echo 'Could not connect to the database. Reason: ' . $e;
}

I even tried to put a stop sigh using codebug but I think it never stops.

Thanks for your help.

Upvotes: 0

Views: 86

Answers (2)

Jay Blanchard
Jay Blanchard

Reputation: 34416

You're missing a closing quote -

'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'].'',
-----------------------------------------------------------------------------^

Note the additional single-quote which balances the line. Error checking would have caught this.

Upvotes: 3

marc_s
marc_s

Reputation: 455

I'm Sorry But I'm Seeing database.php Not databasename.php.
Have You Even Checked If The File Exists?
Also Connecting To The Database Should Be Typed In Config File & You should require It In You're Main PHP File.
For Example The Config File Should Look Like This:

<?php
$connection = mysql_connect('localhost', 'root', 'password');  //here is the host, username and password of mysql account.instead of localhost type in your websites domain name. 
if (!$connection){                                              //and instead of password,type in your own password.
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
    die("Database Selection Failed" . mysql_error());
}
?>

& The Main PHP Should Look Like this:

<?php
require('config.php'); //requires the config.php page
//rest of the code goes here...
?>

Also On Line 10,You Have Missed A Closing Single-Quote.

Upvotes: 0

Related Questions