PDO connection to MySQL database refused - php

I am trying to connect to my NearlyFreeSpeech MySQL database. I can login through PHPMyAdmin but not through PDO. I am using this code
$dbconn = new PDO('mysql:host=127.0.0.1;dbname='.$config['db'].'; port=3307', $config['user'], $config['pass']);
Where $config is defined in a separate file. The error I get is:
Warning: PDO::__construct() [pdo.--construct]: [2002] Connection refused (trying to connect via tcp://127.0.0.1:3307)
Error: SQLSTATE[HY000] [2002] Connection refused
and then eventually
Fatal error: Call to a member function query() on a non-object in...
If I use
mysql:host=localhost
The error I get is
Error: SQLSTATE[HY000] [2002] No such file or directory
Now I assume "Connection refused" is better than "No such file or directory", but I don't know where to go from here. Any idea why this is happening? Thank you for your help.

Try my existing functions and constant variables, you may also change those constant to an array variable you have.
define("SERVER_SQL_VERSION","mysql");
define("SQL_SERVER","localhost");
define("SQL_PORT","3306");
define("SQL_USERNAME","root");
define("SQL_PASSWORD","");
define("SQL_DB_NAME","db");
if(!function_exists('pdoConnect')) {
function pdoConnect() {
$pdo = new PDO(SERVER_SQL_VERSION.":host=".SQL_SERVER.";dbname=".SQL_DB_NAME."", "".SQL_USERNAME."", "".SQL_PASSWORD."");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
There might be an issue about your concatenation, this must be working...
I also seperated the SERVER_SQL_VERSION, and added a functions to check if the driver is available...I am using the XAMPP software and only mysql and sqlite is active, if you/others try to use postgresql and so on...that must be working as well.
if(!function_exists('check_sql_version')) {
function check_sql_version() {
$sql_available = false; //make it false yet
foreach(PDO::getAvailableDrivers() as $key => $val) {
if(SERVER_SQL_VERSION == $val)
{
$sql_available = true;
}
}
//check now if sql_available is true or false
if($sql_available == true)
return true;
else
return false;
}
}
So a sample should be considered:
if(!check_sql_version()) {
echo '('.SERVER_SQL_VERSION.') is not available, you only have this drivers:<br/>';
foreach(PDO::getAvailableDrivers() as $key => $val) {
$key = $key + 1;
echo $key.') '.$val.'<br/>';
}
exit(); //exit and dont proceed
}
$stmt = pdoConnect()->prepare("SELECT * FROM accounts");
$stmt->execute();
I hope it helps!

Related

Access denied for user ''#'localhost' (using password: NO) using AWS and EC2

I am getting the following error when using SHIFTEDIT IDE to try connect to my amazon EC2 instance running LAMP server and mysql server.
The code I am writing in PHP to connect to my sql server is as followed:
<?php
function connect_to_database() {
$link = mysqli_connect("localhost", "root", "test", "Jet");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
}
?>
OUTPUT: Success: A proper connection to MySQL was made! The my_db database is
great. Host information: Localhost via UNIX socket Access denied for
user ''#'localhost' (using password: NO)
I am definitely using the right password for root as I can successfully login when using Phpmyadmin, I just cannot make a connection with PHP for some reason.
Currently, I have a single Amazon ec2 instance with LAMP server and a MySQL server installed. Any help will be much appreciated.
EDIT: I am using Php 5.6.17
When you create a mysqli instance (either by new mysqli(...) or mysqli_connect(....) within a function/method, you have to take php's variable scope into account. Return the mysqli instance from the function and let the caller use and/or assign that instance.
<?php
/*
builds and throws an exception from the error/errno properties of a mysqli or mysqli_stmt instance
#param useConnectError true: use connect_error/connect_errno instead
#throws mysqli_sql_exception always does
*/
function exception_from_mysqli_instance($mysqli_or_stmt, $useConnectError=false) {
// see http://docs.php.net/instanceof
if ( !($mysqli_or_stmt instanceof mysqli) && !($mysqli_or_stmt instanceof mysqli_stmt) {
// see docs.php.net/class.mysqli-sql-exception
throw new mysqli_sql_exception('invalid argument passed');
}
else if ($useConnectError) {
// ok, we should test $mysqli_or_stmt instanceof mysqli here ....
throw new mysqli_sql_exception($mysqli_or_stmt->connect_error, $mysqli_or_stmt->connect_errno);
}
else {
throw new mysqli_sql_exception($mysqli_or_stmt->error, $mysqli_or_stmt->errno);
}
}
/* creates a new database connection and returns the mysqli instance
#throws mysqli_sql_exception in case of error
#return valid mysqli instance
*/
function connect_to_database() {
$link = new mysqli("localhost", "root", "test", "Jet");
// see http://docs.php.net/mysqli.quickstart.connections
if ( $link->connect_errno) {
// a concept you might or might not be interested in: exceptions
// in any case this is better than to just let the script die
// give the other code components a chance to handle this error
exception_from_mysqli_instance($link, true);
}
return $link;
}
try { // see http://docs.php.net/language.exceptions
// assign the return value (the mysqli instance) to a variable and then use that variable
$mysqli = connect_to_database();
// see http://docs.php.net/mysqli.quickstart.prepared-statements
$stmt = $mysqli->prepare(....)
if ( !$stmt ) {
exception_from_mysqli_instance($stmt);
}
...
}
catch(Exception $ex) {
someErrorHandler();
}
and a hunch (because of the actual error message; trying to use the default root:<nopassword> connection, that's the behaviour of the mysql_* functions, not of mysqli):
Do not mix mysqli and mysql_* functions.

Problems connecting to MySQL using PDO

I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'config.php';
// connecting to mysql
try {
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
}
catch (PDOException $e) {
$output = 'Unable to connect to database server.' .
$e->getMessage();
exit();
}
}
// destructor
function __destruct() {
}
public function getAllUsers() {
try {
$sql = "select * FROM gcm_users";
//$result = mysql_query("select * FROM gcm_users");
$result = $this->$db->query($sql);
return $result;
}
catch (PDOException $e) {
$error = 'Error getting all users: ' . $e->getMessage();
}
}
With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12
Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12
Line 12 is:
$this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
TYPO
//$this->$db =
$this->db =
same here
//$this->$db->query($sql);
$this->db->query($sql);
and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

Included mysqli_connect inside a function fails, why?

I've seen a few people with this same issue, yet none of the answers solved my problem. This is what I have in three files:
index.php:
$dbconnect = connectDB("mydb","connect");
mysqli_query($dbconnect,"INSERT INTO `mytable` (field1,field2) values ('value 1','value 2')");
connectDB("","kill",$dbconnect);
functions.php
function connectDB($db_name,$connectorkill,$link) { include('connectDB.inc.php'); }
connectDB.inc.php
$host="localhost";
$user="myusername";
$pass="mypassword";
if($connectorkill == "connect") {
if($dblink = mysqli_connect($host, $user, $pass, $db_name)) {
echo "dblink created.";
return $dblink;
} else { echo "Error connecting to database."; }
} elseif($connectorkill == "kill") { mysqli_close($link); }
and what I get is:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/username/public_html/members/index.php on line 2
which looks like the connectDB function is not doing its job, specifically the return of the $dblink variable in connectDB.inc.php. I went ahead and moved the code from connectDB.inc.php to inside the functions.php and it solved the problem, but I don't want it set up that way. Is there a way to solve this error?
Two solutions:
Solution 1: Refractor your code, something along the lines of:
config.php:
$config = array(
"databases" => array(
"my_database" => array(
"host" => "localhost",
"user" => "myusername",
"pass" => "mypassword"
)
)
);
functions.php:
require("config.php");
function connectDB($dbname)
{
global $config;
if (!isset($config["databases"][$dbname]))
return; // error, database info not in $config
$dbc = $config["databases"][$dbname];
$dbcon = mysqli_connect($dbc["host"], $dbc["user"], $dbc["pass"], $dbname);
if (!$dbcon)
return; // unable to connect error goes here
return $dbcon;
}
Note that this is just the bare minimum of a connectDB function. There really should be more error checking in there (for example, on each of the $dbc keys. It also needs proper error reporting and such, this is just a general hint in the right direction.
Solution 2: Add return in front of your include...
function connectDB($db_name,$connectorkill,$link) { return include('connectDB.inc.php'); }
Regardless of the solution: You really need some error checking code in your index.php because no matter what you do: Your connectDB function isn't always going to return a valid database connection.

Codeigniter alternate database connection if server down

I want to use a raw php code in Codeigniter for alternate database connection my raw php code is:
$db = mysql_connect('remote_server', 'username', 'password'); if(!$db){
$db = mysql_connect('localhost', 'username', 'password') ; }
to connect to a backup server if the remote mysql server is down for some reason.
Has anyone done this kind of thing with CodeIgniter? If so, would you mind sharing code or ideas?
UPDATE:
just figured out a better approach.
suppose you have 2 database configuration in database.php, one is the default, the other is the backup
i.e
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'temp_test1';
//.......
$db['backup']=$db['default'];
$db['backup']['hostname'] = 'localhost1';
$db['backup']['username'] = 'root';
$db['backup']['password'] = '';
$db['backup']['database'] = 'temp_test1';
now, add this to the end of the database.php file
//check to see if you can connect
$conn=#mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
if($conn) //check to see if it's connecting, if it is close this connection
{
mysql_close($conn);
}
else{ //if it isnt
$db['default']=$db['backup']; //replace the default credentials with the backup credentials
}
OLD POST:
there are a lot of approaches you can take.
Your you can check if a particular connection is open via this mysql_ping(), i.e
$conn=mysql_connect(...);
if(mysql_ping($conn)){...};
so you can use this method to decide which database to choose.
For codeigniter, one approach (which is a rather bad one I would say, but an approach none the less), is to mess with the system files. In DB_Driver, in this portion of the code:
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
is where it tries to connect and checks if connection was successful, and if not gives the error.
I'm not sure how you do exception handling in CI, but basically you should handle an exception and connect to a different database.
Since I dont know exception handling, say I create a database_backup.php file the config folder hostname, username, password, and database variable. Then I would change the code to this
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id) //oops, first connection failed
{
//no problem, change the credentials of the database to our backup credentials
$ci=&get_instance();
$ci->load->config('database_backup');
$this->username=$ci->config->item('username');
$this->password=$ci->config->item('password');
$this->database=$ci->config->item('database');
$this->hostname=$ci->config->item('hostname');
//try to connect to database once more
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource STILL?nothing we can do now, throw an error
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}
take a look at system/database/drivers/mysql/mysql_driver.php
find the function function db_connect() [or function db_pconnect() depending upon which one you using]
there is the connection code:
return #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
change the logic to suit your need.
by the way, prefere to use the PDO driver instead as by default, codeigniter uses mysql_* of whose depreciation process started.

Codeigniter/PHP check if can connect to database

I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:
$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);
if(!$db_obj){
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
After terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?
My question was answered on this thread on Codeigniter forums.
The key is to not autoinitialize the database:
$db['xxx']['autoinit'] = FALSE;
To suppress errors it you can set this
$db['xxx']['db_debug'] = FALSE;
Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:
$db_obj = $this->database->load('xxx',TRUE);
$connected = $db_obj->initialize();
if (!$connected) {
$db_obj = $this->database->load('yyy',TRUE);
}
Here is my entire config file for future reference: https://gist.github.com/3749863.
when you connect to database its returns connection object with connection id on successful condition otherwise return false.
you can check it to make sure that database connection is done or not.
$db_obj=$CI->load->database($config, TRUE);
if($db_obj->conn_id) {
//do something
} else {
echo 'Unable to connect with database with given db details.';
}
try this and let me know, if you have any other issue.
I test all I found and nothing wokrs, the only way I found was with dbutil checking if database exists, something like this:
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase'))
echo 'Not connected to a database, or database not exists';
Based on what was said here:
Codeigniter switch to secondary database if primary is down
You can check for the conn_id on the $db_obj
if ($db_obj->conn_id === false) {
$config['db_debug'] = true;
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
This should work.
try {
// do database connection
} catch (Exception $e) {
// DO whatever you want with the $e data, it has a default __toString() so just echo $e if you want errors or default it to connect another db, etc.
echo $e->getMessage();
// Connect to secondary DB.
}
For those who downvoted me, you can do this. Exception will catch PDOException.
try {
$pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
mail('webmaster#example.com', 'Database error message', $e->getMessage());
// and finally... attempt your second DB connection.
exit;
}
$readReplica = #$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
// Failed to connect
}
Im not sure about the error code (not sure if its int/string) and don't have CI nearby to test this out but this principle should work
$this->load->database();
print_r($this->db);
Its work for me
$config['xxx'] = xx;
...
$config['db_debug'] = false;
$db_obj = #$this->load->database($config,true);
if(!#$db_obj->initialize()){
echo "Unable to connect database";
die;
}

Categories