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.
Related
I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.
Connect.php:
<?php
$servername = "//////";
$username = "/////";
$password = "/////";
$conn = oci_connect($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected!";
?>
I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?
Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()
Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.
Download the appropriate oracle client to your machine, extract it and copy and paste in your system drive.
Add the path of your oracle client to environment variables.
Then you need to enable php_oci8_12c extension using php.ini or GUI if available.
Open php file and write the following code:
function connect(){
$dburl = "(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = your_host)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = your_db_sid)
)
)";
//db charset is optional
$db_charset = 'WE8MSWIN1252'; //your db charset goes here
try {
return oci_connect("username", "password",$dburl,$db_charset);
}
catch (Exception $e) {
die($e);
}
}
This code is work fine on my windows 10 machine, php 7.1.9 and oracle 12c.
Forth link in google after searching for your exact questions brought up the following link: http://me2learn.wordpress.com/2008/10/18/connect-php-with-oracle-database/
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.34)(PORT = 1521)))(CONNECT_DATA=(SID=orcl)))" ;
if($c = OCILogon("system", "your database password", $db))
{
echo "Successfully connected to Oracle.\n";
OCILogoff($c);
}
else
{
$err = OCIError();
echo "Connection failed." . $err[text];
}
?>
I have set up an Oracle 18c database and am trying to connect to it from a php file but when I run a simple connection test, I receive a server error where it cant't seem to connect. I ran print_r(getLoaded_extensions()); and from the output array it shows that I am currently not using the oci8 extension as I wanted. My connection test file contains the following
#!/usr/local/bin/php
<?php
putenv("ORACLE_HOME=/usr/lib/oracle/18.3/client64")
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ***.***.*.**)(PORT = 1521)))(CONNECT_DATA=(SID=orcl)))" ;
if($c = OCILogon("username", "password", $db))
{
echo "Successfully connected to Oracle.\n";
OCILogoff($c);
}
else
{
$err = OCIError();
echo "Connection failed." . $err[text];
}
I am unsure whether I set my putenv() wrong to the correct location of the oci.dll file or if I need to install the extension in the first place. Thank you
Since you said that you checked your currently used extensions and OCI8 is not present, I would go ahead and install the module and enable it on your server
Most probably, the 18c default installation creates a Container DB (CDB) called ORCL and PDB1 (pluggable DB)..
Run lsnrctl stat to look for the services created.
then, in DB connection, use service_name instead of SID for connection. The value of service_name can be seen in the output of lsnrctl stat
Example.
$db = "(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = patronus.domain.com)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = pdb1.domain.com)
)
)" ;
I am new to Oracle, installed the Oracle today the 11g Express Edition.
Then I installed Java SDK, and then the free Oracle SQL Developer.
I connected with system account and created a username and table as defined below. I don't exactly know how Oracle works, I think instead of database name, usernames are used. So below are details.
Username/Connection/Database = CustomSearch
Table = Reservation_General_2
There are some columns inside that table and some data. but the point is I cant connect to Oracle Server.
Here is how I tried to connect to database server.
<?php
/**
* Created by PhpStorm.
* User: HaiderHassan
* Date: 9/3/14
* Time: 9:52 PM
*/
header('Access-Control-Allow-Origin: *');
$tns = "
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = orcl)
)
)
";
try {
$conn = new PDO("oci:dbname=".$tns, 'customsearch', 'babaji');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Problem is when I try to open that page, I get this error.
ERROR: could not find driver
These are my connection settings when I connect from Oracle Sql Developer.
What am I doing wrong, what steps should I take to fix this issue?
Update
I added the driver by removing semicolon from the php.ini file
extension=php_pdo_oci.dll
But I started getting this error.
The program can't start because OCI.dll is missing from your computer. Try reinstalling the program to fix this problem.
I have to click 4 time OK for different alert boxes that shows up. I also downloaded oci.dll and copied it to the windows/system32, but still getting this error. What to do?
Update
I uninstalled XAMPP and followed this guide to install Apache and PHP separately,
http://www.oracle.com/technetwork/articles/dsl/technote-php-instant-12c-2088811.html
and then I tried my luck. That driver Problem went away but there is new problem
ERROR: SQLSTATE[HY000]: pdo_oci_handle_factory: ORA-12521: TNS:listener does not currently know of instance requested in connect descriptor (ext\pdo_oci\oci_driver.c:635)
Here below is my new connection String.
try {
$conn = new PDO('oci:dbname=//localhost:1521/xe/ORCL', 'customsearch', 'babaji');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I tried to follow this answer on Stack Overflow for making a connection string.
http://stackoverflow.com/questions/11970261/connect-oracle-with-pdo-with-sid-and-instance-name
Update 2
Also tried to check if drivers installed. I used this code
foreach(PDO::getAvailableDrivers() as $driver)
echo $driver, '\n';
Got this code from this below link
http://stackoverflow.com/questions/23239433/could-not-connect-to-oracle-using-pdo
it echoes this below line
oci\n
So this means that it is installed or this means some drivers are missing?
Update 3
Again rolled back to old connection just changed some stuff in that connection and seems like connection to oracle worked.
try {
$conn = new PDO("oci:dbname=".$tns, 'customsearch', 'babaji');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to database';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
with this I get the message 'Connected to database', means echo works because there is no error given by PDO.
But problem is now my query is not working? What happened to my query? Or will I have to change the syntax of the query also as I connected to Oracle? Or is the connection still not working?
Check PDO and OCI drivers installed properly or not
Try with following code
class PDOConnection {
private $dbh;
function __construct() {
try {
$server = "127.0.0.1";
$db_username = "SYSTEM";
$db_password = "Oracle_1";
$service_name = "ORCL";
$sid = "ORCL";
$port = 1521;
$dbtns = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = $server)(PORT = $port)) (CONNECT_DATA = (SERVICE_NAME = $service_name) (SID = $sid)))";
//$this->dbh = new PDO("mysql:host=".$server.";dbname=".dbname, $db_username, $db_password);
$this->dbh = new PDO("oci:dbname=" . $dbtns . ";charset=utf8", $db_username, $db_password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function select($sql) {
$sql_stmt = $this->dbh->prepare($sql);
$sql_stmt->execute();
$result = $sql_stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function insert($sql) {
$sql_stmt = $this->dbh->prepare($sql);
try {
$result = $sql_stmt->execute();
} catch (PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
if ($result) {
return $sql_stmt->rowCount();
}
}
function __destruct() {
$this->dbh = NULL;
}
}
$dbh = new PDOConnection();
$dbh->select($select_sql);
$dbh->insert($insert_sql);
Have you installed the PDO driver? Look at the output of phpinfo() to see what's installed and/or enabled in your environment.
PDO Installation
If you're running PHP on linux, you can see what PDO drivers are available for your distribution by running yum list php-pdo. You can install the driver by running yum install php-pdo. You may also need to install a database specific driver for your database. Running a yum list php* will show you all the PHP extensions available for installation.
Database Specific Drivers
You need to install instant client on Windows, I used it and it work, see this video, the only that change is in the video when he execute install, you don't have to because in the new zip, doesn't have the execution file. I only have a problem when I make a SELECT query but the connection works just fine.
https://www.youtube.com/watch?v=cZDDI9HFBIU
Contact me if you have any question
I think your problem is with oracle listener configuration, your driver is ok, the error "listener does not currently know of inst.." means there is oracle configuration issue. You must ensure that the parameters in the listener file is exactly the same as in the connection string.
Also your connection string oci:dbname=//localhost:1521/xe/ORCL is incorrect, it should be oci:dbname=//localhost:1521/orcl (host:port/service_name) as indicated in listener.ora file. Ensure the correctness of your connection string using SQL developer.
you may check the below link, this link illustrates the matching of listener.ora and connection string parameters and there is php pdo code snippet at the end with the correct usage of the connection string.
https://www.youtube.com/watch?v=pMQXVihgrrE
https://adhoctuts.com/fix-oracle-io-error-the-network-adapter-could-not-establish-the-connection-error/
Wrong, Wrong & Wrong.
PHPinfo() will NOT enable the PDO driver nor will it show up.
You do NOT need to download a PDO driver separately the one packaged with your PHP installation will work fine.
You do NOT need to install the instant client as your PHP for windows will have the instant client built-in.
Solution:
Updating IIS7 with PHP manager or updating the PHP ini file within your installation to Enable the DLL.
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
extension=php_pdo_sqlsrv.dll
[PHP_PDO_OCI]
extension=php_pdo_oci.dll
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.
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();
}
?>