Development and Production php/MySQL queries management with Mercurial - php

I have a web project I'm versioning with Mercurial and I don't know how to manage access to two different databases; one is for Development purposes and the other one is for Production.
For now my project is still in development, so I access the dev database and make queries on some of its tables with a php script as for example :
<?php
$dbuser = 'something';
$dbpassword = 'something';
$dbname = 'devDBName';
//~ //connect
$link = mysql_connect('servName', $dbuser, $dbpassword);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
metricsName();
function metricsName()
{
$sql = "SELECT id_metric, name_metric FROM metric";
$result = mysql_query($sql); // result set
while($rec = mysql_fetch_array($result, MYSQL_ASSOC)){
$arr[] = $rec;
};
$data = json_encode($arr); //encode the data in json format
echo '({"success": "true", "message" : "OK","data":' . $data . '})';
}
?>
But I don't know how to access a different database for the Production environment, should I make a copy of these PHP scripts and put explicitly the name of the production database? Or is there a way to "parameterize" this?
Any help would be appreciated.

Separate out your code so that the configuration (i.e. database connections, any other environment specific config / code) is kept in one place.
It makes it easier to maintain (as it's kept centrally), and your build / deployment process can deal with which configuration details need to be used.
Clearly your project is at a very early stage, but this approach will help as it grows.

This example is for mysqli, but the idea should apply to the library you are using. in a config.php file do something like:
//define('DB_HOST_NAME', 'prodserver.com');
define('DB_HOST_NAME', "devserver");
define('DB_NAME', "databasename");
define('DB_USER', "username");
define('DB_PW', "password");
you could put some code around the define statements that will check which server the code is running on and determine which database to connect to. If the dev server for the php is different from the prod server for the php.
Then in your database.php do something like
$include_path = $_SERVER['DOCUMENT_ROOT'] . "/someincludedir";
.....
require $include_path . '/config.php';
......
class myDatabase
{
var $db_host_name = DB_HOST_NAME;
var $db_name = DB_NAME;
var $db_user = DB_USER;
var $db_pw = DB_PW;
var $mysqli;
function connect()
{
$this->mysqli = new mysqli
(
$this->db_host_name,
$this->db_user,
$this->db_pw,
$this->db_name
) or die ("mysqli interface failed");
if( mysqli_connect_errno() )
{
printf("COULD NOT CONNECT TO DATABASE -- mysqli connection failed: %s\n", mysqli_connect_error());
}
}
}
Note that the above class assumes it will be a singleton and if you wanted to have multiple connections to the same or different databases you would then parameterize the database, username, etc for the connect function and you could connect to different databases with different objects.

Related

PHP - oci_connect not found

I researched and found out oci_connect() is the way to go. I found out that i could either use the Connect Name from the tnsnames.ora file or use an easy connect syntax. Since my database isn't locally stored and I had no idea where the said, tnsnames.ora file was located in apex.oracle.com, I went with easy connect strings.Here's what I've done so far.
$username = "myemail";
$host = "apex.oracle.com";
$dbname = "name";
$password = "password";
// url = username#host/db_name
$dburl = $username . "#".$host."/".$dbname;
$conn = oci_connect ($username, $password, $dburl);
if(!$conn) echo "Connection failed";
I get a
Call to undefined function oci_connect()
So what would be the way to go?
UPDATE 1:
Here's the list of things I did:
Installed Oracle DB
Unzipped Oracle Instance client
Set the environment variables
Uncommented the extension=php_oci8_12c.dll in php.ini
Copied all the *.dll files from the instance client folder to xampp/php and xampp/apache/bin
also made sure the php/ext folder had the required dlls.
That was last night. I have restarted my PC multiple times, APACHE with it but I'm still getting this error:
Call to undefined function oci_connect()
At this point I'm frustrated and don't know where to go from here. PHP just doesn't seem to link up to oci8. I can view the databases I made from Database Configuration Assistant in cmd from 'sqlplus' command and a few select statements. So everything seems to be setup right, its just the php that's having problems trying to use oci_connect().
My database.php, now is setup as:
public function __construct()
{
error_reporting(E_ALL);
if (function_exists("oci_connect")) {
echo "oci_connect found\n";
} else {
echo "oci_connect not found\n";
exit;
}
$host = 'localhost';
$port = '1521';
// Oracle service name (instance)
$db_name = 'haatbazaar';
$db_username = "SYSTEM";
$db_password = "root";
$tns = "(DESCRIPTION =
(CONNECT_TIMEOUT=3)(RETRY_COUNT=0)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = $host)(PORT = $port))
)
(CONNECT_DATA =
(SERVICE_NAME = $db_name)
)
)";
$tns = "$host:$port/$db_name";
try {
$conn = oci_connect($db_username, $db_password, $tns);
if (!$conn) {
$e = oci_error();
throw new Exception($e['message']);
}
echo "Connection OK\n";
$stid = oci_parse($conn, 'SELECT * FROM ALL_TABLES');
if (!$stid) {
$e = oci_error($conn);
throw new Exception($e['message']);
}
// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
throw new Exception($e['message']);
}
// Fetch the results of the query
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
$row = array_change_key_case($row, CASE_LOWER);
print_r($row);
break;
}
// Close statement
oci_free_statement($stid);
// Disconnect
oci_close($conn);
}
catch (Exception $e) {
print_r($e);
}
}
And it outputs:
oci_connect not found
OCI8 is listed in my phpInfo().
Okay I found out the culprit behind this whole ordeal. I had set the PATH Environment Variables but apparently forgot to add a new system environment variable named TNS_ADMIN and set the directory to PATH/TO/INSTANCE/CLIENT.
Here's the list of System Environment variable you need to add:
Edit PATH system variable and add the $ORACLE_HOME/bin dir
Edit PATH system variable and add the Instance Client dir
Add new system variable, name it TNS_ADMIN and add the Instance Client dir
I hope this helps those who come looking.
First, this has been asked before, but Oracle doesn't allow remote database connections to their free apex.oracle.com example service. Sorry. You can only interact with it through the web interface.
Second, if you do find a remote Oracle db to connect to, you'll need to install the Oracle Instant Client for your OS, and configure the PHP OCI8 extension.

Open DB Connection within PHP Function

I wrote an addon module for our WHMCS billing system a long time ago that we recently realized was causing some issues. Essentially each module's PHP file is loaded regardless if it is actually used or not, where this is how their "hook" system is setup.
When I wrote the module, I included my "db_config.php" file at the top in the global space, which I now realize is causing this database to load every page and is apparently being written to when it shouldn't be. As this is the case, I would like to open the Database connection at the top of the function and close it at the end of the function.
I've never seen this done before nor can I find much information on it. The contents of my db_config.php appear as follows and I am wondering if I can just include_once() inside of the function?
<?php
// Connection's Parameters
$hostname = "xxx.xxx.xxx.xxx";
$database = "database";
$username = "username";
$password = "password";
// Connection
$tca_conn = mysql_connect($hostname, $username, $password);
if(!$tca_conn)
{
die('Cannot Establish Connection to Database : ' . mysql_error());
}
$tca_db = mysql_select_db($database, $tca_conn);
if (!$tca_db)
{
die ('Cannot Select Database : ' . mysql_error());
}
?>
Try this one.It might work for you.
$tca_db = mysql_select_db($database);
instead of
$tca_db = mysql_select_db($database, $tca_conn);

PHP mysql connect to any remove server the post variables

if (!empty($_POST)) {
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$db = $_POST['db'];
echo '<pre>';
print_r($_POST);
$con = #mysqli_connect($host . ":3360", $user, $pass, $db);
// $con=#mysqli_connect('192.168.100.42','root','vertrigo','skates');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo 'connected';
}
#mysqli_close($con);
}
I'm using this script to access remote db server in local(basically i want to access local db server through live webiste), howewer, I'm getting an error:
Failed to connect to MySQL: Unknown MySQL server host
'192.168.100.42:3360' (11004)
Please help to get out from this.
192.168.100.42 looks like a local IP. You'd need to try to connect to your static public IP and then forward port 3306 in your router to the 192.168.100.42 machine.
That's not your only problem;
Just because $_POST is not empty, don't assume it has those array keys set and not empty. Syntax like
if(isset($_POST['user'] && !empty($_POST['user'])))
Is much better.
Also, never use $_POST on any database interaction without sanitisation, and never connect to a database with the root user.
I don't know your exact application, but it's impossibly insecure.

Connecting to a remote mysql server

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();
}
?>

PHP database selection issue

I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.

Categories