Method for selecting different local host database with shared code - php

I'm using this simple function to connect to a named_database. But the code and its associated project are used on more than one site. I'm tired of having to constantly edit the DB_PASS settings etc.
function select_named_db()
{
$link = mysqli_connect( DB_HOST, DB_USER, DB_PASS);
$result=mysqli_select_db( $link, DB_NAME ) ;
return $link;
}
How would I alter my function so that it could try 2 or 3 different database settings so the script can figure out which host, user and password set to use?
Would be it something simple like this?
if (!mysqli_connect( DB_HOST, DB_USER, DB_PASS))
{
$link = mysqli_connect( DB_HOST, DB_USER, DB_PASS);
} elseif (!mysqli_connect( DB_HOST2, DB_USER2, DB_PASS2))
{
$link=mysqli_connect( DB_HOST2, DB_USER2, DB_PASS2);
}
Or is there a better procedural method?

settings.php:
if (ENV == 'dev') {
define('DB_HOST', 'localhost');
// and so on
} elseif(ENV == 'production') {
define('DB_HOST', '127.0.0.1');
// and so on
}
then define ENV somewhere in bootstrap file or webserver config

isn't it better to pass a parameter to select_named_db()?
You could have an array of DB connections:
$DB_HOST[0]=...
$DB_USER[0]=...
and depending the page where you call from, use a DB or another. This parameter could be defined in the function or be passed in session, as you wish...

Related

How connect with mysql database in other server by php

my question is about connect with mysql database in other server by php ??
Server A is rec.misuratau.edu.ly, Server B is alrand.ly , I need to code pls.
I am not sure if I understand well. You are asking how to make a connection to mysql database on two different server?
You can do it like this:
First create databases on server, create user define password and grant access to the user.
Create two separate file: First is Config.php
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'http://rec.misuratau.edu.ly'); // replace with servername
define('DB_NAME', 'db');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
Second is DbConnect.php
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect() {
include_once dirname(__FILE__) . '/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($this->conn,"utf8");
// returing connection resource
return $this->conn;
}
}
LAter you just call the method before sql statements.
Please check the link below as well:
https://www.w3schools.com/php/php_mysql_connect.asp

Unknown error while connecting

I am trying to learn OOP for PHP by following a lynda.com video. The problem is they are using MySQL and I am trying to use MySQLi. I am using xampp set up on my local system with Windows 7. I have a config file that contains the following:
// Database Constants
defined('DB_SERVER') ? null : define("DB_SERVER", "127.0.0.1");
defined('DB_USER') ? null : define("DB_USER", "gallery");
defined('DB_PASS') ? null : define("DB_PASS", "phpOTL123");
defined('DB_NAME') ? null : define("DB_NAME", "photo_gallery");
then I have a database.php file that is to do the connecting:
require_once("config.php");
class MySQLDatabase {
private $conn;
function __construct() {
$this->open_connection();
}
public function open_connection() {
$this->conn = mysqli_connect('.', 'DB_USER', 'DB_PASS','DB_NAME');
// $this->conn = mysqli_connect("127.0.0.1", "gallery", "phpOTL123");
if (!$this->conn) {
die("Database connection failed: " .mysqli_connect_error($this->conn));
} else {
$db_select = mysqli_select_db($this->conn, "photo_gallery");
if(!$db_select) {
die("Database selection failed: " .mysqli_connect_error($this->conn));
}
}
}
as it is it will not connect, but when I try it not using the constants it will. I am getting the following error:
Unknown errror while connecting in C:\xampp\htdocs\sandbox\photo_gallery\includes\database.php on line 12.
Line 12 is
$this->conn = mysqli_connect('.', 'DB_USER', 'DB_PASS','DB_NAME');
I have used MySQLi before in a separate file buy did not use the constants and had no issues. I have tried having them in the same file (database.php) and still got the same error. I have also looked at the other questions that are similar to this and they recommended using
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "config.php");
but this still did not help. Am I missing something with the constants?
You are passing the constant's name as a string, not its value, change it to the following:
$this->conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
using constant don't need quotes.
The hostname should be a FQDN or an IP Address. Also, there shouldn't be any 's enclosing the constants. Please change the line to any of them below:
$this->conn = mysqli_connect('localhost', DB_USER, DB_PASS, DB_NAME);
$this->conn = mysqli_connect('127.0.0.1', DB_USER, DB_PASS, DB_NAME);
Or you need to use the already defined constants!
$this->conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

How to use function to connect to database and how to work with queries?

I am using functions to work with database.. Now the way i have defined the functions are as follows:-
/**
* Database definations
*/
define ('db_type', 'MYSQL');
define ('db_host', 'localhost');
define ('db_port', '3306');
define ('db_name', 'database');
define ('db_user', 'root');
define ('db_pass', 'password');
define ('db_table_prefix', '');
/**
* Database Connect
*/
function db_connect($host = db_host, $port = db_port, $username = db_user, $password = db_pass, $database = db_name) {
if(!$db = #mysql_connect($host.':'.$port, $username, $password)) {
return FALSE;
}
if((strlen($database) > 0) AND (!#mysql_select_db($database, $db))) {
return FALSE;
}
// set the correct charset encoding
mysql_query('SET NAMES \'utf8\'');
mysql_query('SET CHARACTER_SET \'utf8\'');
return $db;
}
/**
* Database Close
*/
function db_close($identifier) {
return mysql_close($identifier);
}
/**
* Database Query
*/
function db_query($query, $identifier) {
return mysql_query($query, $identifier);
}
Now i want to know whether it is a good way to do this or not.....
Also, while database connect i am using
$host = db_host
Is it ok? Secondly how i can use these functions, these all code is in my FUNCTIONS.php The Database Definitions and also the Database Connect... will it do the needful for me...
Using these functions how will i be able to connect to database and using the query function... how will i able to execute a query?
VERY IMPORTANT: How can i make mysql to mysqli, is it can be done by just adding an 'i' to mysql....Like:-
#mysql_connect
#mysqli_connect
With global constants, you can directly use them inside a function. So in this case,
/**
* Database Connect
*/
function db_connect() {
if(!$db = #mysql_connect(db_host . ':' . db_port, db_user, db_pass)) {
return FALSE;
}
if((strlen(db_name) > 0) AND (!#mysql_select_db(db_name, $db))) {
return FALSE;
}
// set the correct charset encoding
mysql_query('SET NAMES \'utf8\'');
mysql_query('SET CHARACTER_SET \'utf8\'');
return $db;
}
And here is how you can implement the client code:
<?php
if(!$conn = db_connect()) {
die('cant connect to mysql');
}
$rs = db_query('SELECT * FROM tableA', $conn);
/* loop through the resultset */
db_close ($conn);
?>
Regarding converting mysql to mysqli, no it might not be that straight-forward; just adding an "i" might not work. MySQLi has different syntaxes. For one, the port is explicitly passed to the connect method rather than appended to the host as done above. Please read the manual.
You should also consider using PDO library as suggested by Simone Vittori.

How to make a mysql connection inside a function

How can I make a mysql connection inside a function if my mysql connect is in another include file?
Here is the mysql connect include file.
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
}
File: DB.php
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
function getConnection() {
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
} else {
return $dbc;
}
}
Other file:
require_once '/path/to/DB.php';
$connection = getConnection();
var_dump($connection->host_info);
you could make $dbc global inside the function.... as long as both files are included it should work fine
#powtac:
I agree on a per case basis, however if you plan on making a more robust database solution for a large site, having one class object (well named is important) can be a powerful tool. That's not to say you couldn't do the same thing and make the object a static variable inside of a function to prevent a careless developer from overwriting it:)
Since you might be calling getConnection a lot, it makes sense to make it static so that it does not get created more than once. Building on powtac's version:
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'adfg');
function getConnection() {
static $dbc;
if (!$dbc) {
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
trigger_error ('Could not connect to MySQL.', E_USER_ERROR);
}
}
return $dbc;
}
You would then include this file and call getConnection wherever it's convenient.
Apart from making $dbc static so that it's only created once, I also removed the MySql error message when a connection cannot be established (it's generally a good idea to not give out such information if your users might see it; errors on connect at development time are relatively rare and can be debugged easily on the spot). Finally, I left the trigger_error and did not replace it with the more usually seen die because it might be part of your error handling framework. However, I did raise the error severity to signify that an error when attempting to connect should be an immediate show-stopper.

PHP function for mysqli connection gives error

Newer to creating php functions and mysql. I have function to connect to a database db_conect_nm(). This is in file db_fns.php, and contains the user and password to connect to my db. I created this to have a more secure db connection. I had it in a directory outside of public_html, and got error PHP Warning: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for user 'negoti7'#'localhost' (using password: NO) ...
Looking for solutions, I saw comments which indicated that perhaps this db user did not have permission from root, so I put it in a directory in public_html, same directory as program where it is being called. I still get the same error.
I have tested the connection without being a function, and it works. What is wrong, and why is this not working as a function? I really want to put this somewhere other than in the code directly and make it more secure.
db_fns.php content
<?php
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
?>
I call it from nm_functions.php, db_fns.php is included there.
nm_functions.php
<?php require_once('sanitizedpathto/db_fns.php');
......some code
$conn_nm = db_connect_nm();
$result_sub = $conn_nm->query("select * from subscribers where uname='$username'");
.... more code
?>
Any ideas?
Thanks
Could it be the scope of the variables? Have you tried defining the variables inside the function to test?
Like this:
<?php
// db connect to nm database
function db_connect_nm()
{
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
?>
You are :
first, declaring some variables, outside of any functions
then, trying to use those variables from inside a function.
Variables declared outside of a function are not, by default, visible from inside that function.
About that, you should read the Variable scope section of the manual.
Two possible solutions :
Use the global keyword, to import those variables into your function -- making them visible
Or define constants, instead of variables -- which makes sense, for configuration values.
In the first case, your function would look like this :
// db connect to nm database
function db_connect_nm()
{
// Make these outside variables visible from inside the function
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
And, in the second case, you'd first define the constants :
define('DB_HOST', 'localhost');
define('DB_DBNAME', 'myname_databasename');
define('DB_USER', 'myname_dbusername');
define('DB_PASSWORD', 'password');
And, then, use those constants :
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DBNAME);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
This second solution is probably more clean than the first one ;-)
Your connection variables are not scoped inside the connection function. You either need to pass them as parameters to the function (preferable) or use the global keyword inside to reference them:
function db_connect_nm($host, $nm_user, $nm_pword, $nm_name)
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}
Alternate, not preferred:
function db_connect_nm()
{
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}

Categories