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
Related
i wrote a php script which should connect me with my database. I also uploaded the files in the public_html section, but it always throws this error :
Warning: mysqli::mysqli(): (HY000/2002): Connection refused in /Applications/XAMPP/xamppfiles/htdocs/FoodHelperSwift/db/public_html.php on line 24
Here is the line : $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
This is my code :
public_html
var $conn = null;
var $result = null;
public $dbhost = null;
public $dbname = null;
public $dbuser = null;
public $dbpass = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpassword;
$this->dbname = $dbname;
}
public function openConnection()
{
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
echo "YESSSS";
echo $this->dbhost;
echo $this->dbuser;
echo $this->dbpass;
echo $this->dbname;
if(mysqli_connect_errno())
{
throw new Exception("Could not connect with database");
$this->conn->set_charset("utf8");
}
}
public function closeConnection()
{
if ($this->conn != null)
{
$this->conn->close();
}
}
}
and
register user
:
require("../db/public_html.php");
$dbhost = "127.0.0.1";
$dbname = "xxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpassword = "xxxxxxx";
$returnValue = array();
if(empty($_REQUEST["userEmail"]) || empty($_REQUEST["userPassword"])
|| empty($_REQUEST["userFirstName"])
|| empty($_REQUEST["userLastName"]))
{
$returnValue["status"]="400";
$returnValue["message"]="Missing required information";
echo json_encode($returnValue);
return;
}
$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);
$salt = openssl_random_pseudo_bytes(16);
$secured_password = sha1($userPassword . $salt);
$dao = new MySQLDAO($dbhost, $dbuser, $dbpassword, $dbname);
$dao->openConnection();
The password etc. is right and i also tried localhost, but then i got an error that he cant find the file maybe you could help me.
Most likely you're not following steps provided by your website hosting provider.
Third party hosting solutions usually require you setup your remote IP
From the error message you specified it looks like you're trying to do this from your own home XAMP web service.
First - the basics
:
localhost - won't work from home - because that's going to look for your own MySQL database not the hosted db
Second - logging in from home (or remotely)
read the docs (always a good idea) Remote access to Bluehost MySQL
Use the following configuration settings for connecting to your database
Host name = (use the server IP address)
Database name = (cpanelUsername_databaseName)
Database username = (cpanelUsername_databaseUsername)
Database password = (the password you entered for that database user)
MySQL Connection Port = 3306
TCP or UDP, either is fine.
Allowing a Remote Server to Access Your Database
Before connecting to MySQL from another computer, the connecting computer must be enabled as an Access Host.
Log into cPanel and click the Remote MySQL icon, under Databases.
Type in the connecting IP address, and click the Add Host button.
Note: You can find and add your IP address directly from this tool. Look for Your IP is: 123.123.12.123 [Add]. Clicking the [Add] link will input your IP into the field box below.
Click Add, and you should now be able to connect remotely to your database.
To troubleshoot this, strip your code down to the basics. Make yourself a little testMyDb.php file, containing only the minimal stuff. For example:
$dbhost = "127.0.0.1";
$dbname = "xxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpassword = "xxxxxxx";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Once you have that working, you can proceed to debug your php class and make sure you are setting things up correctly.
Your file named public_html.php contains some code that's part of a php class implementation (for example __construct()), but I don't see a class ClassName { line to set up a class definition. It's possible you've copied some fragments of code from somewhere without getting it all.
If your simple test DOESN'T work, check with bluehost's tech support krewe. You may need some special credentials or database name to connect to MySQL from one of their Windows hosts.
If you're using the MySQL server on a bluehost machine, and trying to connect to it from your local machine, that will not work (especially not with 127.0.0.1). You'll need to configure bluehost to allow remote MySQL connections, and you'll have to use the actual MySQL hostname.
I typically connect using the following:
$db_host = "localhost";
$db_username = "bill";
$db_pass = "mypassword";
$db_name = "theDB";
mysql_connect("$db_host","$db_username","$db_pass", TRUE) or die(mysql_error());
mysql_select_db("$db_name") or die("no database by that name");
I tried changing the host to the RDS endpoint below with no luck:
$db_host = "mysql7.1234567890123.us-west-2.rds.amazonaws.com";
-The security group has inbound rules that allow my IP.
-I've tried adding "10.0.0.0/8" to the security group from Connecting From PHP Server to MySQL Server on Amazon AWS
Other info: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP_legacy.rds.html
There are couple of things and use PDO or mysqli to connect. If you've made sure that you can connect to RDS by setting the right security group, then you've got the main issues squared away.
Connect to Amazon RDS with this in PHP:
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$dbh = new PDO($dsn, $username, $password);
$link = mysqli_connect($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
Example 1. Example using PDO to connect to an RDS database
$dsn = 'mysql:host=mydbinstance.abcdefghijkl.us-east-1.rds.amazonaws.com;port=3306;dbname=mydb';
$username = 'sa';
$password = 'mypassword';
$dbh = new PDO($dsn, $username, $password);
Example 2. Example using mysqli_connect() to connect to an RDS database
$link = mysqli_connect('mydbinstance.abcdefghijkl.us-east-1.rds.amazonaws.com', 'sa', 'mypassword', 'mydb', 3306);
if nothing works, launch a mysql client like navicat or mysql workbench (free) and punch in all the necessary fields and try to connect and see if it loads the db.
This ended up working for me. Thanks for you help!
$db_host = 'instance2.123456789.us-west-2.rds.amazonaws.com:3306'; //RDS Endpoint...
$db_username = 'myusername';
$db_pass = 'mypassword';
$db_name = 'myDB';
mysql_connect("$db_host","$db_username","$db_pass", TRUE) or die(mysql_error());
mysql_select_db("$db_name") or die("no database by that name");
Im having trouble with MySQLi.
Every time I run this code it returns an error on line 13(mysql_select_bd()).
I cant figure out where the problem is.
Code:
<?php
$conn_error = 'Could not connect';
$mysqli_host = 'localhost';
$mysqli_user = 'root';
$mysqli_password = '';
$mysql_db = 'a_database';
#$mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_password);
mysqli_select_db('a_database', $mysqli_conn);
?>
You have an incorrect usage of the function:
mysqli_select_db('a_database', $mysqli_conn);
The connection must come first before the database name in the arguments:
mysqli_select_db($mysqli_conn, 'a_database');
// ^ connection object, then database name
Alternatively, you could also do this:
$mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_password, $mysql_db);
Or the object oriented interface:
$mysqli_conn = new mysqli($mysqli_host, $mysqli_user, $mysqli_password, $mysql_db); // personal preference
Instead of doing that you can do something like this:
$conn = mysqli_connect('localhost', 'root', '', 'a_database');
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";
?>
How would I connect to the demo phpmyadmin server in php? My code looks like this.
<?php
$host = 'http://demo.phpmyadmin.net/STABLE/';
$dbname = 'shubham';
$user = 'root';
$pass = '';
// Attempt to connect to database.
try {
$DBH = new PDO("mysql:host={$host};dbname={$dbname}", $user, $pass);
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
but I get this as my error
QLSTATE[HY000] [2005] Unknown MySQL server host 'http://www.demo.phpmyadmin.net/STABLE/' (1)
You seem to be confusing two things:
the demo phpMyAdmin front-end that is backed by a db server and db/schema
the db server and schema itself
PDO needs the latter, the db server itself.
Inspecting the front-end code of the demo, I don't see anything in there that would give us the actual connection details for the db server. And that's as I would expect: I find it hard to believe that the makers/maintainers of the phpMyAdmin demo would make their actual db server available for public remote connections.
change your hostname from
$host = 'http://demo.phpmyadmin.net/STABLE/';
to your original remote hostname like eg $host = 'ukld.db.5510597.hostedresource.com';
MySQL does not work on HTTP
<?php
$host = 'demo.phpmyadmin.net';
// High chances that this is NOT your mysql hostname.
// It will not even by like /STABLE/ as you mentioned it.
$dbname = 'shubham';
$user = 'root';
$pass = '';
// Attempt to connect to database.
try {
$DBH = new PDO("mysql:host={$host};dbname={$dbname}", $user, $pass);
} catch(PDOException $e) {
echo $e->getMessage();
}
?>