I'm working on a project where I need to test a remote MySQL connection and if it fails, then I need the code to switch over to using a local MySQL connection. The problem I'm running into is the code always displays the error which really kills the end-user experience.
Things I've tried:
try and catch exception <- got it to display a custom message, but nothing else.
suppressing the error with an # <- this really really affected the loading of the page.
yelling at the computer <- didn't work, but I felt better.
Code:
//-----Remote MySQL Server-----------
$rem_host="99.99.999.999"; //Host Name
$rem_user="testUser"; //MySQL Username
$rem_pass="testPass"; //MySQL Password
$rem_db="testDb"; //Database Name
//----Local MySQL Server-----------
$local_host="127.0.0.1"; //Host Name
$local_user="testLocal"; //MySQL Username
$local_pass="passLocal"; //MySQL Password
$local_db="localDb"; //Database Name
$remoteConnection = mysqli_connect("$rem_host","$rem_user","$rem_pass","$rem_db");
if(!$remoteConnection){ $check_connection=0; }
else{ $check_connection=1; mysqli_close($remoteConnection); }
if($check_connection==1){
$db_host = $rem_host; //Host Name
$db_user = $rem_user; //MySQL Username
$db_pass = $rem_pass; //MySQL Password
$db_name = $rem_db; //Database Name
}
else{
$db_host = $local_host; //Host Name
$db_user = $local_user; //MySQL Username
$db_pass = $local_pass; //MySQL Password
$db_name = $local_db; //Database Name
}
?>
Change line number 2 as per your choice. First i get URL and then check it has "localhost" word then i follow localhost detail (I am using localhost/ in local machine ). If $actual_link cannot get localhost then follow online detail
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($actual_link,'localhost') !== false)
{
//local db detail
$servername='localhost';
$dbusername='root';
$dbpassword='';
$dbname='db_gbook';
echo "local";
}
else
{
//online db detail
$servername='localhost';
$dbusername='dbaname';
$dbpassword='dbpassword';
$dbname='yourdbname';
echo "web";
}
global $link;
$link=mysql_connect ("$servername","$dbusername","$dbpassword");
if(!$link)
{
die("Could not connect to MySQL");
}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
echo "Succesive";
?>
Related
I have an php file, and I want to connect it to Database
usually I use localhost but I never use php in Bluemix
what should I fill these attributes ?
$DB_HOST = 'localhost'; // what should I write instead of
$DB_USER = '';
$DB_PASSWORD = '';
$DB_DATABASE = 'MyDataBase';
please help
First: You Create a folder .bp-config/options.json in the parent folder
and add below line, of code in the options.json folder, so sqli connect will working.
{
"PHP_EXTENSIONS": ["mysqli"]
}
Now make a connection:
$DB_HOST = '127.0.0.1:3307'; // insert ip with port number
$DB_USER = 'user';
$DB_PASSWORD = 'password';
$DB_DATABASE = 'dbname';
$mysqli = new mysqli($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);
$result = $mysqli->query(" SELECT * FROM table_name ");
$row = $result->fetch_assoc();
Create your database service on Bluemix and BIND it to your application. Go to your applications dashboard and you should see the database service instance below. Click on Show Credentials.
However, the right way to do this is to programmatically get the credentials by parsing the VCAP_SERVICES environment variable. See this example:
https://github.com/IBM-Bluemix/php-mysql See db.php
You have to parse db information from VCAP_SERVICES.
If your database service is "SQL Database" you can connect to SQLDB using this example code:
//parse VCAP_SERVICES Environment variable
$vcap_services = $_ENV["VCAP_SERVICES"];
$services_json = json_decode($vcap_services,true);
$sqldb = $services_json["sqldb"];
if (empty($sqldb)) {
echo "No sqldb service instance is bound. Please bind a sqldb service instance";
return;
}
//Get Credentials object (db,host,port,username,password)
$sqldb_config = $services_json["sqldb"][0]["credentials"];
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".
$sqldb_config["db"].
";HOSTNAME=".
$sqldb_config["host"].
";PORT=".
$sqldb_config["port"].
";PROTOCOL=TCPIP;UID=".
$sqldb_config["username"].
";PWD=".
$sqldb_config["password"].
";";
$conn = db2_connect($conn_string, '', ''); //db connection
I am trying to connect mysql database to a php program. I used following program to establish connection. But it is not giving any error even I make any mistake with the code.
<?php
// creating database connection
$dbhost ="localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "my_new";
//connection
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//testing connection
if(mysqli_connect_errno()){
die ("database connection failed :".
mysqli_connect_error() .
"(".mysqli_connect_errno().")"
);
}
?>
In my computer, your code is work well. And I find that mysql_connect will not throw exception.
my I am trying to make login registration page in php.
apache and mysql is up and running.
I am executing the following code
<?php
$db_host = "localhost:777";
$db_username = "root";
$db_pass = "";
$db_name = "login";
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("$db_name") or die ("no database");
?>
I am using localhost:777 because port 80 is being used by skype.
phpMyAdmin is up and running.
The output i am getting is nothing but the above code only.
can anyone help me on this issue?
Use MySQLi or PDO not MySQL.
You're passing the variables as a string using " " in the mysql_connect function
The syntax is as follows: mysqli_connect(host,username,password,dbname,port,socket);
<?php
$db_host = "localhost";
$db_port = "777";
$db_username = "root";
$db_pass = "";
$db_name = "login";
$conn = mysqli_connect($db_host,$db_username,$db_pass,$db_name,$db_port);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Try that and it should work. Please make sure you understand the code above and the error you made. Do not simply copy and paste please you will not learn from it.
I am working on a php mysql connect script.
I wanted it to use functions so I can keep a track what is what, so Mysql connect got one function.
When I run it, I get first "No database selected" and when I specify it manually, it says "Access denied for # localhost".
Code
<?php
/* Mysql Data */
$MySqlUser = "root";
$MySqlPass = "**********";
$MySqlHost = "localhost";
$MySqlDataBase = "serveradmin";
/* End Mysql Data */
function MySqlConnect() {
$Connect = mysql_connect($MySqlHost, $MySqlUser, $MySqlPass);
$Database = mysql_select_db($MySqlDataBase);
if (!$Connect | !$Database) {
die("Cannot connect ".mysql_error());
}
}
MySqlConnect()
?>
So the problem, what causes this? I want the script to be nice and clean, and not sure if function() causes it.
This will fix it, but please look into PDO or mysqli
<?php
/* Mysql Data */
$MySqlUser = "root";
$MySqlPass = "**********";
$MySqlHost = "localhost";
$MySqlDataBase = "serveradmin";
/* End Mysql Data */
function MySqlConnect($MySqlUser, $MySqlPass, $MySqlHost, $MySqlDataBase ) {
$Connect = mysql_connect($MySqlHost, $MySqlUser, $MySqlPass);
$Database = mysql_select_db($MySqlDataBase);
if (!$Connect | !$Database) {
die("Cannot connect ".mysql_error());
}
return $Database;
}
$Database = MySqlConnect($MySqlUser, $MySqlPass, $MySqlHost, $MySqlDataBase );
?>
I have created an html form (demo.html) & POST it's value to a php file (demo1.php). Then i created database in MySQL & wrote connection code in the php file (demo1.php) but it gives the following error
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'#'localhost' (using password: YES) in C:\xampp\htdocs\demo1.php on line 8
Error connecting to mysql
<?php
// contact to database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
//$conn = mysql_connect("localhost","root","password") or die ('Error connecting to mysql');
$dbname = 'test';
mysql_select_db($dbname,$conn);
//$connect = mysql_connect("localhost", "root", "pass") or die ("Error , check your server connection.");
//mysql_select_db("test");
//Get data in local variable
$v_name=$_POST['name'];
$v_email=$_POST['email'];
$v_msg=$_POST['msg'];
// check for null values
if ($v_name=="" or $v_msg=="")
echo "All fields must be entered, hit back button and re-enter information";
else{
$query="insert into contact(name,email,msg) values('$v_name','$v_email','$v_msg')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
mysql_close($conn);
}
?>
Password for user root is incorrect.
Default password on local (home) server is empty, so I think this can help:
$dbpass = '';
The error is pretty explicit - the username/password combination youre using is incorrect. IF thisis a fresh install you need to set a password and/or create a new user.
mysqladmin
User Creation
Granting Privileges
Setting Passwords
For Local Xampp username-root password --''
<?php
// contact to database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
?>
The main reason for this is that the password is wrong. Did you specify the root password when setting up xampp? If not, then leave the password blank as delphist states above