Connecting to Oracle database from PHP - php

I have an Oracle database that I am trying to connect to.
For some reason when I try the following code:
<?php
include "header.php";
// simply attempt to connect to the database
/* If you are connecting to the Oracle database, the credentials are as follows:
* Username: ********
* Password: ********
* Hostname: **********
* Port: 1521
* Service name: ***********
*/
$oracleConnect = true;
if ($oracleConnect)
{
echo 'Attempting connection...<br>';
$connection = null;
try
{
$connection = oci_connect('user',
'pass',
'user#//hostname:1521/dbname');
}
catch (Exception $e)
{
echo $e->getMessage();
}
if (!$connection)
{
echo '<p>Something is wrong.</p>';
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// if the connection has been established
else
{
// tell the user and close it (this is a test)
echo 'Connection established!!';
oci_close($connection);
}
}
else
{
$connection = new mysqli('host', 'user', 'password', 'database');
echo ($connection) ? 'Database connection successful!' : 'Could not connect.';
}
include "footer.php";
?>
When I try the above code, I get the "Attempting connection..." to print, but nothing else. It is supposed to print something else regardless. What could possibly be going wrong?

I think the problem is the user# part of your connection string. I dont think thats necessary as oci_connect has a user name parameter. I could be wrong, ive never used oracle from php before, but the docs on oci connections would also seem to indicate that:
To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.
Also oci_connect does not throw an exception as far as i can tell so your try/catch is useless unless you planned on throwing your own when it returns false.

Related

how to connect to remote database in php pdo

This is view of my phpmyadmin web server
I need to connect to my university webserver on PHPmyadmin which is "phpmyadmin.newnumyspace.co.uk"
what changes are required to achieve this. I mean i know localhost would be changed and port and something needs to be put here but help me out as i don't understand the syntax
<?php
$db_host="localhost";
$db_user="root";
$db_password="";
$db_name="nbl";
try{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
Your sql DB is local to the web host as they are both run on a linux XAMPP server. Obviously include the correct username and password.
function getConnection() {
try {
/* connects to the SQL DB */
$connection = new
PDO("mysql:host=localhost;dbname=unn_w19038752",
"unn_w19038752", "Password");
$connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
/* displays an error if unable to connect */
throw new Exception("Connection error ". $e->getMessage(), 0, $e);
}
}
Then you can just call this function everytime you need to make a connection
($dbConn = getConnection();)
Although for a clearer answer you're better speaking to your KF4009 Module tutor for assistance (That's what you're paying Uni fees for :-) )
Regards, former NU Student :-)
P.S. nbl is a table not a db, and you don't have root access(username), check your email from newnumyspace for your correct server login details.

Access denied for user ''#'localhost' (using password: NO) using AWS and EC2

I am getting the following error when using SHIFTEDIT IDE to try connect to my amazon EC2 instance running LAMP server and mysql server.
The code I am writing in PHP to connect to my sql server is as followed:
<?php
function connect_to_database() {
$link = mysqli_connect("localhost", "root", "test", "Jet");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
}
?>
OUTPUT: Success: A proper connection to MySQL was made! The my_db database is
great. Host information: Localhost via UNIX socket Access denied for
user ''#'localhost' (using password: NO)
I am definitely using the right password for root as I can successfully login when using Phpmyadmin, I just cannot make a connection with PHP for some reason.
Currently, I have a single Amazon ec2 instance with LAMP server and a MySQL server installed. Any help will be much appreciated.
EDIT: I am using Php 5.6.17
When you create a mysqli instance (either by new mysqli(...) or mysqli_connect(....) within a function/method, you have to take php's variable scope into account. Return the mysqli instance from the function and let the caller use and/or assign that instance.
<?php
/*
builds and throws an exception from the error/errno properties of a mysqli or mysqli_stmt instance
#param useConnectError true: use connect_error/connect_errno instead
#throws mysqli_sql_exception always does
*/
function exception_from_mysqli_instance($mysqli_or_stmt, $useConnectError=false) {
// see http://docs.php.net/instanceof
if ( !($mysqli_or_stmt instanceof mysqli) && !($mysqli_or_stmt instanceof mysqli_stmt) {
// see docs.php.net/class.mysqli-sql-exception
throw new mysqli_sql_exception('invalid argument passed');
}
else if ($useConnectError) {
// ok, we should test $mysqli_or_stmt instanceof mysqli here ....
throw new mysqli_sql_exception($mysqli_or_stmt->connect_error, $mysqli_or_stmt->connect_errno);
}
else {
throw new mysqli_sql_exception($mysqli_or_stmt->error, $mysqli_or_stmt->errno);
}
}
/* creates a new database connection and returns the mysqli instance
#throws mysqli_sql_exception in case of error
#return valid mysqli instance
*/
function connect_to_database() {
$link = new mysqli("localhost", "root", "test", "Jet");
// see http://docs.php.net/mysqli.quickstart.connections
if ( $link->connect_errno) {
// a concept you might or might not be interested in: exceptions
// in any case this is better than to just let the script die
// give the other code components a chance to handle this error
exception_from_mysqli_instance($link, true);
}
return $link;
}
try { // see http://docs.php.net/language.exceptions
// assign the return value (the mysqli instance) to a variable and then use that variable
$mysqli = connect_to_database();
// see http://docs.php.net/mysqli.quickstart.prepared-statements
$stmt = $mysqli->prepare(....)
if ( !$stmt ) {
exception_from_mysqli_instance($stmt);
}
...
}
catch(Exception $ex) {
someErrorHandler();
}
and a hunch (because of the actual error message; trying to use the default root:<nopassword> connection, that's the behaviour of the mysql_* functions, not of mysqli):
Do not mix mysqli and mysql_* functions.

Mongodb connectivity error

<?php
/**
* Connects to MongoDB server.
* Stops code execution on`enter code here` connection error.
*
* You do not need to use this file, just any place to globally assign a MongoDB instance to $db.
*
* Define constants in your config or here
*/
define('MDB_USERNAME', 'root');
define('MDB_PASSWORD', 'asd');
define('MDB_HOST', 'localhost:80');
define('MDB_NAME', 'abc');
if (!class_exists('Mongo')) {
die("Mongo class not existing. Did you install the PHP MongoDB extension?");
}
try {
$conn = new MongoClient("mongodb://".MDB_USERNAME.":".MDB_PASSWORD."#".MDB_HOST."/".MDB_NAME);
$conn->authenticate('root','gynadfehurbo');
$db = $conn->selectDB(MDB_NAME);
} catch (MongoConnectionException $e) {
die($e->getMessage()); // In production you might want to turn this off.
}
Mongodb connectivity problem.
while am trying to connect mongodb with php got authentication problem ..By giving port the above error is replaced as connection refused .then i changed the port that error has been replaced as
Failed to connect to: localhost:80: Read timed out after reading 0 bytes, waited for 60.000000 seconds
$server = "mongodb://localhost:27017/dbname"; // Connecting to server
$c = new MongoClient($server );
if($c->connected)
echo "Connected successfully";
else
echo "Connection failed";

How to connect with SLIM REST api with MS SQL server?

I am trying to get results from an API call using Slim connecting with MSSQLSERVER2012
the example used to work with MYSQL getconnection function (see below) but when I am trying to
connect with MsSQL server 2012 I am getting an error like "api call error "invalid data source name"
http://localhost/msapi/api.php/clients
1'api call error "invalid data source name"
require '/Slim/Slim.php';
$app = new Slim();
$app->get('/clients', 'getClients');
$app->run();
function getClients() {
$sql = "select * FROM clients";
try {
$db = getConnection();
$stmt = $db->query($sql);
$clients = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"client": ' . json_encode($clients) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection_MYSQL() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getConnection() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO ("ADODB.Connection");
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$dbhost.";UID=".$dbuser.";PWD=".$dbpass.";DATABASE=".$dbname;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->open($connStr); //Open the connection to the database
return $dbh;
}
the function getConnection_MYSQL() is an example that works.
But the getConnection() tryis to connect with MS SQL server ?
Do you see why I am getting an "invalid data source name" with the function getConnection()?
Since you didn't post an alternative DSN-string, I'm assuming you are using the one from your example and just replace host, username and password. This won't work.
When you are running your Slim-application on a windows host you can (and should) use Microsoft's SQL Server Driver for PHP (sqlsrv).
There are 2 versions sqlsrv.dll and pdo_sqlsrv.dll. When you want to reuse most of your code you should use the latter. This way you probably only have to modify your DSN (see php docs):
new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");
If you are using the first you have to update the way you connect to the db and create the query. You can read the Beginner's Guide to see a few examples that should make it easy.
If you are running not running your application on a Windows-machine you will probably have to set up ODBC and FreeTDS and then use PDO with an ODBC-DSN. From my experience this will be quite a lot of work, but there are a few good tutorials out there. Just google for "freetds sql server".

Codeigniter/PHP check if can connect to database

I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:
$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);
if(!$db_obj){
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
After terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?
My question was answered on this thread on Codeigniter forums.
The key is to not autoinitialize the database:
$db['xxx']['autoinit'] = FALSE;
To suppress errors it you can set this
$db['xxx']['db_debug'] = FALSE;
Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:
$db_obj = $this->database->load('xxx',TRUE);
$connected = $db_obj->initialize();
if (!$connected) {
$db_obj = $this->database->load('yyy',TRUE);
}
Here is my entire config file for future reference: https://gist.github.com/3749863.
when you connect to database its returns connection object with connection id on successful condition otherwise return false.
you can check it to make sure that database connection is done or not.
$db_obj=$CI->load->database($config, TRUE);
if($db_obj->conn_id) {
//do something
} else {
echo 'Unable to connect with database with given db details.';
}
try this and let me know, if you have any other issue.
I test all I found and nothing wokrs, the only way I found was with dbutil checking if database exists, something like this:
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase'))
echo 'Not connected to a database, or database not exists';
Based on what was said here:
Codeigniter switch to secondary database if primary is down
You can check for the conn_id on the $db_obj
if ($db_obj->conn_id === false) {
$config['db_debug'] = true;
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
This should work.
try {
// do database connection
} catch (Exception $e) {
// DO whatever you want with the $e data, it has a default __toString() so just echo $e if you want errors or default it to connect another db, etc.
echo $e->getMessage();
// Connect to secondary DB.
}
For those who downvoted me, you can do this. Exception will catch PDOException.
try {
$pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
mail('webmaster#example.com', 'Database error message', $e->getMessage());
// and finally... attempt your second DB connection.
exit;
}
$readReplica = #$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
// Failed to connect
}
Im not sure about the error code (not sure if its int/string) and don't have CI nearby to test this out but this principle should work
$this->load->database();
print_r($this->db);
Its work for me
$config['xxx'] = xx;
...
$config['db_debug'] = false;
$db_obj = #$this->load->database($config,true);
if(!#$db_obj->initialize()){
echo "Unable to connect database";
die;
}

Categories