Try Manual Connection - php

I have a form with fields to make a connection to the database using CodeIgniter. The data is filled in by the users in the form.
Is it possible to know if the connection is established or not?
$drive = $this->input->post('drive');
$hostname = $this->input->post('hostname');
$database = $this->input->post('database');
$username = $this->input->post('username');
$password = $this->input->post('password');
$base = $this->input->post('base');
$db = array(
'hostname' => $hostname,
'username' => $username,
'password' => $password,
'database' => $database,
'dbdriver' => $drive,
'db_debug' => FALSE);
$cn = $this->load->database($db);
if ($cn) { echo 'ok'; } else {echo 'nops';}

You are explicitly disabling error messages with the 'db_debug' => false, so I don't think you will get CI complaints. However you can do the same as the Database library does for connection testing (since every field is public):
// your original code here
$conn_success = $cn->conn_id ? true : false;

Related

How to get php-native handle from Doctrine\DBAL\Connection?

Given the code
$connectionParams = array(
'dbname' => $this->dbname,
'user' => $this->dbuser,
'password' => $this->dbpass,
'host' => $this->dbhost,
'driver' => 'mysqli',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
var_dump($conn);
How can I get the underlying mysqli handle from $conn (which is a Doctrine\DBAL\Connection)?
I have found *a way* to access it, but its obviously not the way it's supposed to be done, so I'm up for suggestions:
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
foreach((array)$conn->getWrappedConnection() as $mysqli){
// TODO: find official way of getting the handle.
// here we are casting it to (array) to access its PRIVATE PROPERTIES
// it's a fugly hack.
break;
}
var_dump($mysqli);
You can get it this way:
$mysqli = $conn->getWrappedConnection()->getWrappedResourceHandle();

How to connect localhost database to another server database and insert form value using codeigniter? [duplicate]

This question already has an answer here:
Datebase error mysqli::real_connect(): (HY000/2002): Connection refused codeingiter
(1 answer)
Closed 2 years ago.
<?php
$active_group = 'default';
$query_builder = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'campus';
$db['default']['password'] = 'Mac#123';
$db['default']['database'] = 'campusnew';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = TRUE;
$db['otherdb']['hostname'] = "101.51.150.42";
$db['otherdb']['username'] = 'software';
$db['otherdb']['password'] = 'Lmsnew';
$db['otherdb']['database'] = 'lmsnew';
$db['otherdb']['dbdriver'] = "mysqli";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = TRUE;
model function
public function newusersignin()
{
$DB2 = $this->load->database('otherdb', TRUE);
$firstName=$this->input->post('firstName');
$lastName=$this->input->post('lastName');
$timezone=$this->input->post('timezone');
$fullname=$firstName.' '.$lastName;
$email=$this->input->post('email');
$phone=$this->input->post('phone');
$ip_address=$this->input->ip_address();
$institutional=$this->input->post('institutional');
$pass=$firstName.mt_rand(1,100);
$username=$email;
$password=$this->hash($pass);
$insertnewuser= array('name' =>$fullname,'email'=>$email,'phone'=>$phone,'username'=>$username,'password'=>$password,'usertype'=>'ClgAdmin','create_date'=>date('y-m-d H:i:s'),'create_userID'=>1,'create_username'=>'campus','systemadminactive'=>0,'timezone'=>$timezone,'status'=>1 );
$this->db->insert('admin',$insertnewuser);
$DB2->insert('admin',$insertnewuser);
}
In this question I am simply create two database connection one is for localhost and another one is IP which is hosted on different server. Now, what happen when I am going to insert form data in my IP Server then it throw an error and i.e.
Message: mysqli::real_connect(): (HY000/2002): Connection refused
I don't know why this happen? How can I solve this problem? Please help me.
Thank You
Instead of doubling everything in two arrays, can you check against the URL?
Just change the localhost to be more specific as to which db you need to connect too
$is_local = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}";
if (strpos($is_local, 'localhost') !== false) {
// LOCAL
$db_name = "db_name";
$db_user = "root";
$db_pass = "root_pass";
$db_host = "localhost";
} else {
// OTHER
$db_name = "db_name_2";
$db_user = "root_live";
$db_pass = "root_pass_live";
$db_host = "mysql.live.com";
}
Then your connection code is always the same from then
Database Configuration
CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php in the respective environment config folder.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
Inserting Data
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
Your database configuration and methodology given above are correct. All you have to do is allow remote connection for your database on your server. If you are using CPanel, you can browse to "Remote MySQL" and add access host. Add your ISP IP address to allow only your computer or "%" for any computer to access.

How to replace database configuration in codeigniter?

I Have mad an installer for my website. but I don't how to replace hostname,username, password and database. with the values which are coming from input fields.
This is the code from config/database.php file.
$db['default'] = array(
'dsn' => '',
'hostname' => 'db_host',
'username' => 'db_user',
'password' => 'db_pass',
'database' => 'db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
but this code gives me that error.
and this code in controller.
function configure_database() {
// write database.php
$data_db = file_get_contents('./application/config/database.php');
// session_start();
$data_db = str_replace('db_name', $_POST['dbname'], $data_db);
$data_db = str_replace('db_user', $_POST['username'], $data_db);
$data_db = str_replace('db_pass', $_POST['password'], $data_db);
$data_db = str_replace('db_host', $_POST['hostname'], $data_db);
file_put_contents('./application/config/database.php', $data_db);
}
You could format the config/database.php as follows :
$db['default']['username'] = "%USERNAME%";
$db['default']['password'] = "%PASSWORD%";
$db['default']['database'] = "%DATABASE%";
$db['default']['hostname'] = "%HOSTNAME%";
$db['default']['dbdriver'] = "mysqli";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
Then write to it using this method :
function configure_database() {
// write database.php
$data_db = file_get_contents('config/database.php');
// session_start();
$temporary = str_replace("%DATABASE%", $_POST['dbname'], $data_db);
$temporary = str_replace("%USERNAME%", $_POST['username'], $temporary);
$temporary = str_replace("%PASSWORD%", $_POST['password'], $temporary);
$temporary = str_replace("%HOSTNAME%", $_POST['hostname'], $temporary);
// Write the new database.php file
$output_path = './application/config/database.php';
$handle = fopen($output_path,'w+');
// Chmod the file, in case the user forgot
#chmod($output_path,0777);
// Verify file permissions
if(is_writable($output_path)) {
// Write the file
if(fwrite($handle,$temporary)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
Basically it checks on every line for a match and then replace them with the posted data, and lastly write it to the database config again.
Reference : CodeIgniter Installer
If you would like to dynamically set a config item or change an existing one, you can do so using:
$this->config->set_item('item_name', 'item_value');
Where item_name is
the $config array index you want to change, and item_value is its
value.
So you can try this:
// validate the input
if(isset($_POST['dbname']){
$this->config->set_item('hostname',$_POST['dbname']);
}
...

Reading DB credentials in Laravel from files outside laravel core

Sorry if the question is trivial for someone but I wasn't be able to make it and to find answer so far. In Laravel we have DB credentials in app/config/database.php
'connections' => array(
...
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'myDB',
'username' => 'myUser',
'password' => 'myPass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
...
),
Now I have 2 custom files one in public directory and one in libraries directory which also got db credentials in them
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
Is there a way somehow to include app/config/database.php in those files and read DB credentials from instead of have DB credentials in 3 files?
If test.php would live inside your public folder:
// test.php
$config = include __DIR__ . '/../app/config/database.php';
// var_dump($config);
$servername = $config['connections']['mysql']['host'];
$username = $config['connections']['mysql']['username'];
$password = $config['connections']['mysql']['password'];
$dbname = $config['connections']['mysql']['database'];
$conn = new mysqli($servername, $username, $password, $dbname);
You could include the app/config/database.php file and then read the credentials from there.
Inside your custom files it would just be a matter of using include 'path_to/app/config/database.php'; and then you can access the connections array from there. To help us generate a file path we can use the __DIR__ magic constant;
include __DIR__ . '/../app/config/database.php';
$conn = new mysqli(connections['mysql']['host'], connections['mysql']['username'], connections['mysql']['password'], connections['mysql']['database']);

connecting to alternate database when primary database is down?

$servername1 = "localhost1";
$username1 = "user1";
$password1 = "pwd";
$dbname1 = "dbs1";
$servername2 = "localhost2";
$username2 = "user2";
$password2 = "ped2";
$dbname2 = "dbs2";
// Create connection
$conn = new mysqli($servername1, $username1, $password1, $dbname1);
// Check connection
if ($conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2, $dbname2);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
}
Can this type of connection be implemented?? when i implement this deliberately making an error in first database credentials i get a warning that Unknown MySQL server host 'localhost1'
and doesn't load the page. why is this not working?
I make a list of databases and then iterate through them and try to connect. It should be no problem using multiple databases. Using localhost1 and localhost2 (only localhost is possible which is 127.0.0.1) is not possible. You should use IP addresses.
Here is the code:
<?php
$Databases = array(
0 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database1',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_3,
),
1 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database2',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_2,
),
2 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database3',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_1,
),
);
for($i=0;$i<count($Databases);$i++)
{
if($last_db_ind>=count($Databases)){
$last_db_ind=0;
}
if(($db =& db_connect($last_db_ind++))==false){
echo 'Connection failed for DB: '. $Databases["db_name"] . ', DB index: '.$last_db_ind;
continue;
}
?>
You should either use "localhost" or an IP address to connect to the SQL server. In your case it tries to connect to "localhost1" (as in you variable) which doesn't exists (unless you changed your host file). Try using IPs (127.0.0.1 for localhost and any other for the backup)
Cheers,
JCK
You Can try Ping first.
OR
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")
" . $mysqli->connect_error;
}
OR
extension_loaded("mysql");

Categories