php - error connecting to MYSQL

450

Here is the config.php file

<?php

error_reporting(E_ALL ^ E_NOTICE);

/*=========== Database Configuraiton ==========*/

$db_host = "localhost";
$db_user = "test";
$db_pass = "test";
$db_name = "dbtest";


/*=========== Website Configuration ==========*/

$defaultTitle = 'testing';
$defaultFooter = date('Y').' &copy; testing';

?>

Here is the reference to config.php

<?php


require_once "includes/config.php";
require_once "includes/connect.php";
require_once "includes/helpers.php";



header('Cache-Control: max-age=3600, public');
header('Pragma: cache');
header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");

?>

Connect.php is below

<?php

/*
        The login details are taken from config.php.
*/

try {
    $db = new PDO(
        "mysql:host=$db_host;dbname=$db_name;charset=UTF-8",
        $db_user,
        $db_pass
    );

    $db->query("SET NAMES 'utf8'");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    error_log($e->getMessage());
    die("A database error was encountered");
}


?>

Does anyone see the problem with this code? I am getting the error message from connect.php "a database error was encountered" I need another set of eyes because all my info looks correct and I can't see the error in the code. Thanks.

121

Answer

Solution:

you simple change UTF-8 to utf8..

try {
      $db = new PDO(
              "mysql:host=$db_host;dbname=$db_name;charset=utf8",
              $db_user,
              $db_pass
            );
375

Answer

Solution:

Once try with your credentials directly instead of using them as variable.

also try to debug using below:

catch(PDOException $e) {
    error_log($e->getMessage());
    die("A database error was encountered -> " . $e->getMessage() );
}

Let me know if it works.

520

Answer

Solution:

Has it worked before ? I guess your problem is that "localhost" needs to be "127.0.0.1" or similar.

831

Answer

Solution:

$db->query(...) is for SELECT and you are setting a param.

Try

$db->exec(...) instead and that could solve.

People are also looking for solutions to the problem: php - How to order a MYSQL query by another query?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.