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.
Related
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
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);
I have installed WAMP server on my local machine and I have written php script to insert record into the database, but I'm getting the following error-
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\wamp\www\test_services\db_connect.php on line 32
following is my db_config code
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "test_db"); // database name
define('DB_SERVER', "localhost"); // db server
?>
Here is my **db_connect.php code**
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close()
{
// closing db connection
mysql_close();
}
}
?>
Please help.. Thank you..!
I don't think you are showing the correct file. The problem is in db_connect.php. It is very likely that that file does not include db_config.php, i.e:
require_once 'path/to/db_config.php';
Edit: Does db_config.php actually live in the same directory as db_connect.php? Your code suggests that it does, which may be incorrect?
Edit: What happens if you put $var = 'hello' in db_config.php, and then print $var in db_connect.php after you include it, do you see 'hello'? Just to clarify you are connecting with the file..
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...
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.