Unknown error while connecting - php

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);

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

undefined constant DB_SERVER - assumed 'DB_SERVER'

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..

Method for selecting different local host database with shared code

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...

How to switch between 2 mysql databases if one of them was not connected?

I have 2 database servers DRC and Production server..
I connected php config file with the Production server ip to connect its database (it is working fine),
and i made an if statement if production database is not connected, not selected or dropped then go and connect with the DRC server to get its database.
the code below make this action it is working fine for switching 2 databases on local host but it is not connecting to the DRC database if the Production one is not available.
//Production constants
defined ('DB_SERVER')? null : define ("DB_SERVER" , "20.20.10.1");
defined ('DB_USER') ? null : define ("DB_USER" , "root");
defined ('DB_PASS') ? null : define ("DB_PASS" , "rootpass");
defined ('DB_NAME') ? null : define ("DB_NAME" , "dbname");
//DRC constants
defined ('DB_SERVER_DRC')? null : define ("DB_SERVER_DRC" , "20.20.10.2");
defined ('DB_USER_DRC') ? null : define ("DB_USER_DRC" , "root");
defined ('DB_PASS_DRC') ? null : define ("DB_PASS_DRC" , "rootpass");
defined ('DB_NAME_DRC') ? null : define ("DB_NAME_DRC" , "dbname");
function __construct() {
$this->open_connection();
}
public function open_connection() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$this->connection) {
$this->open_connection_DRC();
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if (!$db_select) {
$this->open_connection_DRC();
}
}
}
public function open_connection_DRC() {
$this->connection = mysql_connect(DB_SERVER_DRC, DB_USER_DRC, DB_PASS_DRC);
if (!$this->connection) {
die("Database connection failed: " . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME_DRC, $this->connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}
Any solution or other way to do that, Waiting for your positive response guys.
mysql_connect - Returns a MySQL link identifier on success or FALSE on failure. That's what you can do according to my knowledge. if it returns false connect to the other database.
Can you try with below change in open_connection_DRC function, as per PHP manual you need to pass 5th Boolean argument $new_link as true, when you are trying to open multiple connections.
I am assuming here, that you are connected to production sever and database is not there on production server, so you are trying to open new mysql connection to DRC server.
public function open_connection_DRC() {
$this->connection = mysql_connect(DB_SERVER_DRC, DB_USER_DRC, DB_PASS_DRC, true);
Also it is better to unset $this->connection once you found out that DB is not present on production server.

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.

Categories