简体   繁体   中英

PHP file included but code not working

I am trying to connect mysql from within PHP function. The credentials are stored in a separate PHP file, which I am including it inside the function. But when I run the script, I am getting following error:

Warning: mysql_query(): A link to the server could not be established in C:\xamp
p\htdocs\abc\test.php on line 12. Access denied for user 'ODBC'@'localhost' (using password: NO)    


private function insertToMysql()
{
    include_once('connect_db.php');

    $connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
    mysql_select_db(DB_DATABASE, $connection) or die('Database error -> ' . mysql_error());

    //Queries

}

I tried echoing the include_once and it returned 1. This means, the connect_db.php is included, but somehow the constants are not loaded. What could be the issue??? The credentials are perfect and I verified them. I am not a newbie to PHP.

Contents of connect_db.php:

<?php
  define('DB_SERVER', 'localhost');
  define('DB_USERNAME', 'root');
  define('DB_PASSWORD', '<MyPassword>');
  define('DB_DATABASE', 'testdb');
?>

remove connection handler

private function insertToMysql()
{
    include_once('connect_db.php');

    mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
    mysql_select_db(DB_DATABASE) or die('Database error -> ' . mysql_error());

    //Queries

}

Seems like $connection is a local variable, you can fix this by making it global.

Do this like this.

include_once('connect_db.php');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection) or die('Database error -> ' . mysql_error());

function insertToMysql()
{
    //Queries
    mysql_query('Some query');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM