PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 7, 2022

[FIXED] Error Connecting to Database via PHP

 March 07, 2022     mamp, php     No comments   

Issue

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.


Solution

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.



Answered By - marc_s
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing