php switching to server connection if localhost failed - php

I'm trying to write a script that connects to an online server if localhost connection failed or inaccessible. I have the script below that connects to a localhost database and if it's not accessible then reroute to a server connection. The script somehow fails to work and I just don't know why. Anyone has any suggestions?
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'admin';
$DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
if(!$DB_CON_A) {
die($DB_CON_A);
$DB_HOST = 'www.xyz.com';
$DB_USER = 'admin';
$DB_PASS = '1235kasK';
$DB_NAME = 'admin';
}
try {
$DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}

Here is my solution for those who's looking for one:
<?php
function ping($DB_HOST) {
exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
return $rval === 0;
}
$DB_HOST = 'www.xyz.com';
$connected = ping($DB_HOST);
if ($connected) {
$DB_HOST = 'www.xyz.com';
$DB_USER = 'user';
$DB_PASS = 'pass';
$DB_NAME = 'accounts';
} else {
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'accounts';
}
// Create database if not exists
$DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
$DB_CON_C->query("USE $DB_NAME");
try {
$DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>

Related

Failing testing database connection in php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}

Using global for database conection not working

Ok. Hello guys
I have some problems with my database connection and using it in php.
My normal file structure:
db.php
$mysql_server = "server";
$mysql_user = "user";
$mysql_password = "password";
$mysql_db = "name";
$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno) {
exit();
}
$db->set_charset("utf8");
functions.php file
require_once("db.php");
function func_name() {
global $db;
//doing my work here with $db;
}
I'm 100% sure the credentials i user are ok so this is not the problem.
Can you give me some advice regarding this? I used this structure for every project and now i'm losing my mind trying to figure it out. I bet is something that i missed!
please, help! Thank you!
try using below code !!!
<?php
$mysql_server = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_db = "dbName";
$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno)
{
exit();
}
$db->set_charset("utf8");
function func_name() {
global $db;
$sql = "SELECT text FROM tableName";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["columnName"];
}
} else {
echo "0 results";
}
}
func_name();
mysqli_close($db);
?>

Function for connecting to mysql database

I made my first function for connecting to mysql database. I have index.php and functions.php and i included functions.php to index.php!
This is my Connect to database function...
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", $username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dhb;
}
I don't know is it correct and if i am calling it right.
I type in index.php
<?php
require_once 'functions.php';
connect_to_database();
active_links();
include 'includes/head.php';
include 'includes/nav.php';
..................
See comments:
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
$dbh = false; // initialized for error
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1",
$username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
// consider to exit / throw own exception / stop continuing script anyhow ....
}
// returns false on error
return $dbh; // typo here, was $dhb !!
}
Usage:
$DB = connect_to_database();
if ( $DB !== false )
$DB->function();
So it works fine now, here is the answer! Thank you for help
I created file named config.php
// PDO connect *********
function connect()
{
$host = 'localhost';
$db_name = 'database_name';
$db_user = 'root';
$db_password = '';
return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
and just calling connect function like this, $pdo = connect(); or any name for var but that is the way!
<?php
include 'config.php';
$pdo = connect();
........

Multiple database connection using php userdefined function

This is the code for config.php I am including this file in all php files:
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
mysql_select_db('test1', $conn) or die('Could not select database.');
return $conn;
}
db_connect1();
?>
Here i need to connect with another one database test2.
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for another connection
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn1 = mysql_connect($db_name, $db_user, $db_pass);
$conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
mysql_select_db('test1', $conn1) or die('Could not select database test1.');
mysql_select_db('test2', $conn2) or die('Could not select database test2.');
$conn = new stdClass();
$conn->conn1 = $conn1;
$conn->conn2 = $conn2;
return $conn;
}
$conn = db_connect1();
Then to query database test1, do this:
mysql_query('select * from tablename', $conn->conn1);
and for database test2:
mysql_query('select * from tablename', $conn->conn2);
?>
try this
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1($dbname) {
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
if($conn) {
mysql_select_db($dbname, $conn) or die('Could not select database.');
return $conn;
} else {
die("Error occurred while connect to the server.");
}
}
Every time you call the function and set argument.
echo db_connect1('test1');
echo db_connect1('test2');
Echo the function because you are using return keyword and checked that if it returns 1 its means your server connection is ok.

Unidentified variable after being declared

I'm getting this error
Fatal error: Non-static method Connect::connect() cannot be called statically in D:\xampp\htdocs\Panel\core\init.php on line 63
Here is my code
<?php
class Connect{
public $db_host = "localhost";
public $db_user = "root";
public $db_pass = "";
public $db_name = "panel";
public function connect(){
if(mysql_connect($db_host, $db_user, $db_pass)){
if(mysql_select_db($db_name)){
return true;
}else{
die(mysql_error());
}
}else{
die(mysql_error());
}
return false;
}
}
?>
How do I make the function static?
I tried adding 'static' to the function scope, but I got another error
Thanks :)
You have to pass the variables to function as parameter
function connect($db_host, $db_user, $db_pass,$db_name)
And call this function as
connect($db_host, $db_user, $db_pass,$db_name);
Edit
By seeing your pastebin, you are calling class variables, you have to use $this->variale_name to access them.
<?php
class Connect{
public $db_host = "localhost";
public $db_user = "root";
public $db_pass = "";
public $db_name = "panel";
public function connect(){
if(mysql_connect($this->db_host, $this->db_user, $this->db_pass)){
if(mysql_select_db($this->db_name)){
return true;
}else{
die(mysql_error());
}
}else{
die(mysql_error());
}
return false;
}
}
?>
PDO
<?php
class Connect{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
private $db_name = "panel";
private $dbh = false;
public function connect(){
if ($this->dbh === false)
$this->dbh = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
return $this->dbh;
}
}
?>
You have to declare the variables inside the function like this
<?php
function connect(){
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "panel";
if(mysql_connect($db_host, $db_user, $db_pass)){
if(mysql_select_db($db_name)){
}else{
die(mysql_error());
}
}else{
die(mysql_error());
}
}
?>
Or you can pass the parameters in the function like this
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "panel";
connect($db_host,$db_user, $db_pass, $db_name);
function connect($db_host,$db_user, $db_pass, $db_name){
if(mysql_connect($db_host, $db_user, $db_pass)){
if(mysql_select_db($db_name)){
}else{
die(mysql_error());
}
}else{
die(mysql_error());
}
}
?>
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "panel";
These variables are global and can't be accessible in function connect. If you have to use these global variables then use keyword global . Then these vars will be available within the function.
function connect(){
global $db_host, $db_user, $db_pass, $db_name ;
if(mysql_connect($db_host, $db_user, $db_pass)){
if(mysql_select_db($db_name)){
}else{
die(mysql_error());
}
}else{
die(mysql_error());
}
}

Categories