How to connect to Oracle database? - php

How do you connect to Oracle using PHP on MAC OS X?

I would think OCI would be the way to go. PHP has a module for it.

The PDO abstraction layer can be used to connect to, and perform actions on, an Oracle DB. Here's an article on how to use PDO with Oracle from the Oracle website.
It's also possible to use OCI.
The Oracle PHP Development Centre will have lots more useful information on using Oracle and PHP together.

For instantclient on osx 10.6 64bit do the following:
download the instant client librarys and sdk, stuff it all in a folder. Make sure you get the 64 bit library if you are on a 64 bit machine, 32bit won't work!
- test with sqlplus first
create this if it does not exist
sudo vi /etc/launchd.conf
and add to following to the file(with your own path!)
setenv DYLD_LIBRARY_PATH /usr/oracle_instantClient64
You probaby need to restart your system at this point for launchd to pass the path to apache to pick up the path, or see if restarting launchd works, though i have a feeling that will restart your system anyway!
You should add "extension=oci8.so" to php.ini
sudo vi /etc/php.ini
if that file does not exist copy php.ini.default
sudo cp /etc/php.ini.default /etc/php.ini
then add the above extension, there is a section with lots of extensions further down the file, put it there somewhere
oci requires a library symlink so do
sudo ln -s $DYLD_LIBRARY_PATH/libclntsh.dylib.10.1 $DYLD_LIBRARY_PATH/libclntsh.dylib
Also theres some wierd hardcoded library link in the oracle binaries so fix that
mkdir -p /b/227/rdbms/
Its only looking for the oracle libraries so link it back
ln -s /usr/oracle_instantClient64/ /b/227/rdbms/lib
now install oci8 from pear repository. If you have installed snow leopard osx 10.6 without upgrading you may have problems with pear and pecl. If so you will need to install pear first. see: https://discussions.apple.com/thread/2602597?start=0&tstart=0
sudo pecl install oci8
HINT: don't use autodetect, specify the instantclient path when it asks you..
instantclient,/usr/oracle_instantClient64
restart apache
sudo apachectl graceful
test by navigating to the URL in a browser or you can call the file directly on the command line
php index.php
thats it
use the following as a test file..
<?php
$dbHost = "localhostOrDatabaseURL";
$dbHostPort="1521";
$dbServiceName = "servicename";
$usr = "username";
$pswd = "password";
$dbConnStr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=".$dbHost.")(PORT=".$dbHostPort."))
(CONNECT_DATA=(SERVICE_NAME=".$dbServiceName.")))";
if(!$dbConn = oci_connect($usr,$pswd,$dbConnStr)){
$err = oci_error();
trigger_error('Could not establish a connection: ' . $err['message'], E_USER_ERROR);
};
$strSQL = "SELECT SYSDATE FROM DUAL";
$stmt = oci_parse($dbConn,$strSQL);
if ( ! oci_execute($stmt) ){
$err = oci_error($stmt);
trigger_error('Query failed: ' . $err['message'], E_USER_ERROR);
};
while(oci_fetch($stmt)){
$rslt = oci_result($stmt, 1); print "<h3>query returned: ".$rslt."</h3>";
}
?>

I dont know the Mac specifically, nor PHP, but you usually need to install the Oracle Client tools (Instant Client).
http://www.oracle.com/technology/tech/oci/instantclient/index.html
Once installed you modify the TNSNAMES.ORA file to point to the server and instance name of the Oracle database.
Then you can use the PHP "database connection" stuff (sorry) to create a connection and running your SQL statements.
Use the SQL*PLUS client to check the connection works:
ie.
c:> SQLPLUS
CONNECT scott/tiger#mydatabase
If the TNSNAMES.ORA is correct you should get a connection, or at least "username/password incorrect" that proves you got communication with the Oracle instance.
If you get TNS-12521 (?) errors then your TNSNAMES.ORA is incorrect.

Connecting to an oracle database should be no problem with the oci-interface, using "oci_connect()" for example.
Further examples are here:
http://php.net/manual/en/oci8.setup.php
But I do not understand, what the remark MAC OS X means - are you running an apache locally?
Hope this helps,
Bastian

Related

Call to undefined function sqlsrv_connect() when connecting Microsoft SQL management studio 2014 with php [duplicate]

I have come across quite a few post regarding the same subject question, however I am still unable to resolve it and so I ask. I am trying to connect to sql in my php script. My connection string is:
/* Specify the server and connection string attributes. */
$serverName = "xxx-PC\SQLExpress";
$connectionOptions = array("Database"=>"Salesforce");
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false)
{
die(print_r(sqlsrv_errors(), true));
}
I have installed and included the following in my php.ini file located under the wamp folder: C:\wamp\bin\php\php5.4.16:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
My wampserver is running fine and so are the wampapache and wampsqld services. I am able to execute php.exe successfully. However I am unable to make the connection to SQL Server 2008 R2 where my database is located. Please help!
EDIT 1: The wamp server is running the wampmysql service while I am trying to connect to SQL Server 2008 R2. Could this be the reason? Should I be using MySQL instead of SQL? Any pointers?
EDIT 2: I do not see sqlsrv section at all when I run phpinfo() though I have added extension=php_sqlsrv_54_ts.dll in the php.ini file located in the bin folder of the wamp server.
When you install third-party extensions you need to make sure that all the compilation parameters match:
PHP version
Architecture (32/64 bits)
Compiler (VC9, VC10, VC11...)
Thread safety
Common glitches includes:
Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
Forgetting to restart Apache.
Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
This helped me get to my answer. There are two php.ini files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin folder. When connecting to SQL through sqlsrv_connect function, we are referring to the php.ini file in the apache folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use
PHP 5.3.6, or later.
PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not
with PHP 5.4. If possible, use PHP 5.2.13, or later.
Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.
First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.
i have same this because in httpd.conf in apache PHPIniDir D:/wamp/bin/php/php5.5.12 that was incorrect
Search for sqlsrv extension in pdo_sqlsrv.
Got it fixed. Even though I specified the folder that everything was stored, in my case C:\shared it turns out that PHP was just looking in c:\ for the lumina-online-dependencies folder.
I copied it to C:\ and it now works
I'm using MAMP and PHP 8.1 on Windows 10. I needed to download the SQL Server drivers from Microsoft (https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver16), and then extract and copy the proper driver dll in this folder:
C:\MAMP\bin\php\php8.1.0\ext
(Side note: Laravel uses PDO.)
And then reference it:
In this file:
C:\MAMP\conf\php8.1.0\php.ini
Add this line:
extension=php_pdo_sqlsrv_81_ts_x64.dll
And in this file:
C:\MAMP\bin\php\php8.1.0\php.ini
Add this line:
extension=pdo_sqlsrv_81_ts_x64
And of course restart the services / Apache.
Then I could connect like this:
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
Hope that helps someone else!

How can I connect to an external (another server) Oracle Database using PHP? [duplicate]

I got this error.
Fatal error: Call to undefined function oci_connect()
$conn = oci_connect('localhost', 'username', 'password') or die(could not connect:'.oci_error)
that is the code.
This is the error I got.
Fatal error: Call to undefined function oci_connect() in C:\xampp\htdocs\org\org\php\myphp.php on line 51
I checked the PHP DLL files in ext folder.
I just spend THREE WHOLE DAYS fighting against this issue.
I was using my ORACLE connection in Windows 7, and no problem. Last week I Just get a new computer with Windows 8. Install XAMPP 1.8.2. Every app PHP/MySQL on this server works fine. The problem came when I try to connect my php apps to Oracle DB.
Call to undefined function oci_pconnect()
And when I start/stop Apache with changes, a strange "Warning" on "PHP Startup" that goes to LOG with "PHP Warning: PHP Startup: in Unknown on line 0"
I did everything (uncommented php_oci8.dll and php_oci8_11g.dll, copy oci.dll to /ext directory, near /Apache and NOTHING it works. Download every version of Instant Client and NOTHING.
God came into my help. When I download ORACLE Instant Client 32 bits, everything works fine. phpinfo() displays oci8 info, and my app works fine.
So, NEVER MIND THAT YOUR WINDOWS VERSION BE x64. The link are between XAMPP and ORACLE Instant Client.
Simple steps
You need to enable the below extension in your php.ini
;extension=php_oci8.dll
;extension=php_oci8_11.g.dll
by removing the ";" so that the results will below:
extension=php_oci8.dll
extension=php_oci8_11.g.dll
Download Oracle Instant Client:- Preferably 32 bit. 32 bit will also work on 64 bit. You can just google: download oracle instant client windows 32 bit. Use version 11 of the client because extension=php_oci8_11.g.dll won't work with 12. Unzip the package into a location such as C:\Oracle\instantclient_11_2.
Finally modify the System's PATH Environment Variable with end location, under system variables not user variables
Then you need to restart the System for PATH changes to fully propagate.
If you just restart XAMPP/WAMP without restarting the machine the Client's DLL files (i.e. OCL.dll) will not be loaded (nor found)
by PHP's php_oci8_11g.dll extension.
You need to enable that extension in your php.ini file. See Oracle Installation:
extension=oci8.so
Things to Make sure
Whenever you connecting Oracle Database , try to use 32 Bit oracle client libraries, Since XAMP PHP is compiled with 32 Bit(Though you have 64 Bit windows Machine)
Download Oracle Client from Download From here
Paste it in C:\instantclient_12_1
Then Set the path to above in System Environment Variable
Then Go to C:\xampp\php\php.ini and uncomment extension=php_oci8_12c.dll
Then Restart the XAMP and it should work without any Issue.
I installed WAMPServer 2.5 (32-bit) and also encountered an oci_connect error. I also had Oracle 11g client (32-bit) installed. The common fix I read in other posts was to alter the php.ini file in your C:\wamp\bin\php\php5.5.12 directory, however this never worked for me. Maybe I misunderstood, but I found that if you alter the php.ini file in the C:\wamp\bin\apache\apache2.4.9 directory instead, you will get the results you want. The only thing I altered in the apache php.ini file was remove the semicolon to extension=php_oci8_11g.dll in order to enable it. I then restarted all the services and it now works! I hope this works for you.
Check your php –version as like as PHP 5.6.32 (cli) (built: Oct 25 2017 16:02:15).
Using the OCI8 extension to access Oracle Database. So Download php_oci8.dll from 1https://pecl.php.net/package/oci8/2.0.8/windows. (5.6 Thread Safe (TS) x86 ) php_oci8.dll must be the same version with your php version.Then unzipped it and you will find
1.php_oci8.dll
2.php_oci8_11g.dll (as per your oralce version) these two file pasted into your
(xampp\php\ext) folder.
Open your php.ini file and add these
extension=php_oci8.dll
extension=php_oci8_11g.dll
Check your oracle version and service name using these commands
Open your cmd
sqlplus / as sysdba
select * from v$version;
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production, our oracle version is 11g so we can use instantclient_11_1 (Instant Client 32-bit) downloads from https://www.oracle.com/technetwork/topics/winsoft-085727.html
show parameter service_name;
service_name is orcl (you should remember this service name)
After downloading instantclient_11_1 unzipped it and then pasted in your Local Disk. And copy the path C:\instantclient_11_1 and then set this path as your user variable & system variable. Note is that my code is working without setting path variable.
Open your cmd and enter into SQL, create your schema following these commands
sqlplus / as sysdba
create user dbname identified by pass123;
grant connect,resource to dbname;
Create table user_info and insert data into your table and commit out.
Note: you must commit your data either data is not inserted.
Then this script run in your htdocs
<html>
<head><title>Oracle demo</title></head>
<body>
<?php
// Create connection to Oracle
$conn = oci_connect("dbname", "pass123", "//localhost/orcl"); // orcl is your service_name
$query = 'select * from user_info';
$stid = oci_parse($conn, $query);
$r = oci_execute($stid);
// Fetch each row in an associative array
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {
print '<tr>';
foreach ($row as $item) {
print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : '&nbsp').'</td>';
}
print '</tr>';
}
print '</table>';
I installed Wamp & expected everything to work out of the box. Not so.
I have 2 Oracle clients on my x64 Windows machine (instant and full). If anyone else has a similar setup, the trick is to make sure the instant client is (a) in your Path environment variable and (b) precedes the full client in the Path variable. There's a really brief section on Windows here but it gave the answer.
Alright, folks.
First, use
<?php
phpinfo();
?>
and determine your PHP Version (located at the very top, e.g. 7.0.xxx)
and also, your PHP Version architecture: x64 or x86
and also, Thread Safe or Not THread Safe (located in the first table as "Thread Safety".) "Disabled" obviously means "Not Thread Safe".
It is absolutely critical that the following three pieces of software that you will need are:
for the same major version of PHP (7.0 for 7.0.xxx)
same version of Oracle as the version you are accessing (11g, 12g, etc)
the same Not Thread Safe / Thread Safe version of PHP
all for the same architecture.
If any of the following are for a different architecture, Not Thread Safe/Thread Safe version, PHP major version number, or database version, you'll get errors:
1. PHP for Windows
2. OCI8 PECL Drivers for PHP (https://pecl.php.net/package/oci8)
3. Oracle Instant Client
Remember: If you are connecting to an 11g Oracle instance, you need an 11g driver.
Second, install the correct PHP, OCI8 PECL Driver, and instant client.
I chose:
d:\php\ for php
d:\oci\ for instant client
unzip the contents of the OCI8 PECL Driver into d:\php\ext\
Third, modify d:\php\php.ini according the instructions given by Oracle:
1. set the extension directory
2. set only one of the following:
a. for 11g drivers, use extension=php_oci8_11g.dll
b. for 12c drivers, use extension=php_oci8_12c.dll
c. for other oracle DB drivers, use the correct oracle extension.
Fourth: Add d:\oci\ (or whatever your instant client install location is) to your system PATH.
Fifth: reboot your PC.
Sixth, on a command prompt, type "where oci*" and verify that your Instant Client install path version of oci.dll is present.
Seventh, go to d:\php\ and type "php -m" and you should see OCI8 in the list.
If you do not see OCI8 in the list of modules after typing "php -m", open up d:\php\errorlog.txt
If you see something like:
PHP Warning: PHP Startup: Unable to load dynamic library 'ext\php_oci8_11g.dll' - %1 is not a valid Win32 application.
then either instant client or your PECL driver download is not the same architecture as your PHP version.
If you see something like:
PHP Warning: PHP Startup: Unable to load dynamic library 'ext\php_oci8_12c.dll' - The specified procedure could not be found.
then you are using the wrong OCI8 PECL driver for your version of instant client.
Hope this helps.
1 - The first step is to identify the right instant client for your xampp or wampp or lampp installation through checking PHP details from phpinfo. Create a simple php file and add the code below and preview on your browser.
<?php
phpinfo();
?>
phpinfo() details
2 - Go to https://www.oracle.com/database/technologies/instant-client/downloads.html and download the right instant client (base package and sdk) for your architecture (32bit or 64bit)
Instant client package - basic
Instant client package - SDK
3 - Extract instantclient to your preferred directory and add the path to your environment variables.
4 - Go to php.ini and enable oci8 extension by removing the ; at the start of the line.
Look for this line
;extension=php_oci8_12c.dll ; Use with Oracle Database 12c Instant Client
Refactor to
extension=php_oci8_12c.dll ; Use with Oracle Database 12c Instant Client
Environment variables
5 - Restart your PC
6 - Check your phpinfo (The page you created on step 1). You should see the details below:
OCI8
try this
in the php.ini file uncomment this
extension_dir = "./" "remove semicolon"
I had the same issue, the solution on this page helped me, it's caused by using incompatible oci ddl files.
Hope it helps.
Download xampp and uncomment oracle 12c extension or 11c 'extension=oci8_11g' for xampp 7.2.9
Download instant client 32 bit and set its path
Download instant client 32 bit SDK package and set its path
Copy instant clients and SDK dll files to xamp\php\ext, xampp\php\ and xampp\appache\bin\
Download php-oci of same php version of tread safe x86 then copy its files to php\ext*.dll,
php version is written on top of phpinfo tab of xampp admin.
OCI8 will appear on phpadmin page or apache admin then phpadmin tab. It means phpOCI has been installed.
Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":
instantclient-basic-windows.x64-12.1.0.2.0.zip
instantclient-sqlplus-windows.x64-12.1.0.2.0.zip
instantclient-sdk-windows.x64-12.1.0.2.0.zip
This will create the following folder "C:\Oracle\instantclient_12_1".
Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.
Then Restart your server.

Connecting php server to DB2 from outside IBM Cloud

I am following the process as described here:
https://www.ibm.com/support/knowledgecenter/en/SSHRBY/com.ibm.swg.im.dashdb.doc/connecting/connect_connecting_php.html
I have completed the instalation and I have even run the validation command in shell
db2cli validate -dsn DashDB -connect -user bluadmin -passwd 'your_secret_password'
see output below
But still my www page crashes on the line
$conn = odbc_connect( $conn_string, "", "" );
becasue it does not recognize the odbc_connect function.
Any feedback and hopefully help is very welcome.
Your question is not about programming, but instead it is about configuration.
It is best if you detail your php version and your linux distro details fully every time you ask for help.
You already successfully configured db2dsdriver.cfg and successfully validated a CLI connection to the remote Db2 database. That is essential.
The next step is to ensure that both ODBC and PHP are configured appropriately.
It may help to verify all the following items:
Verify php-odbc is installed to match your version of php . Use the package-manager (e.g. yum or apt etc.) for your linux distro to install it, there's plenty of pages to help you with that.
Verify the php.ini has enabled: extension=odbc.so ( for Linux it seems this is not default with php7).
Verify that the command-line php -m shows that odbc is loaded
If you configured a unixODBC DSN then verify you can successfully connect to the DSN with isql command on linux (to verify that your odbc.ini and odbcinst.ini are properly configured with the Db2 driver and the DSN details). Use odbcinst -j to show the path to odbc.ini and odbcinst.ini for your distro. There's plenty of pages to show how to configure those files, and how to run the isql command line. Usage of a DSN is optional, but it can help with sanity checking and centralises the connection strings instead of having them replicated in php scripts.
verify the ibm_db2 driver is loaded and pdo_ibm (if using PDO interfaces) with the php -m command line.

PHP on Ubuntu loads MSSQL extension from command line but NOT when run through Apache

I've been searching and trying for quite a while to find an answer, so will finally ask here.
I have a UBUNTU install from Turnkey LINUX, PHP Ver 5.6.23.
I have compiled and enabled mssql.so as I require to connect to a MSSQL server.
My simple connect PHP script is so:
$server = 'rslocal';
$connect = mssql_connect($server, 'sqluser', 'sqlpassword');
if (!$connect) {
echo 'can not connect';
}
I can run the above PHP script from the command line and it is successful.
I can also run the FreeTDS tsql utility and connect and query the server from the command line
When I run it from the browser through Apache, it tells me
Fatal error: Call to undefined function mssql_connect() ...
I have checked that php --ini (cli) and phpinfo() (browser) both report the same ini file in use.
I am not running SELinux so the setbool commands are not relevant here, however the problems stated by others where SELinux WAS the issue are exactly the same as mine, so perhaps this is a place to start.
My feeling is that it is a security policy or something stopping the extension from loading any function that wants to communicate with an outside server, but I am stuck.
Any help would be appreciated.
I found the "answer". On this distro, Ubuntu 14.x, the command
sudo apachectl restart
doesn't seem to be enough to reload php. The php.ini change, specifically adding extension=mssql.so had not been not applied when run through apache. This raises the question how to "hard" restart Apache so php.ini changes take, but that's a different question. I only noticed that it worked after a reboot.

Using mssql methods (FreeTDS, PHP and Apache on Mac OS X)

I have installed FreeTDS on my Mac, but I'm having some issues connecting using mssql_connect.
First, when I run tsql -C I see that the freetds.conf directory is listed as /opt/local/etc/freetds. I have a freetds.conf file inside this directory.
Next, if I connect like this:
$connect = mssql_connect('IP_ADDRESS', 'username', 'password');
then everything works as expected. That is, I can retrieve, update, insert data from/into whichever DB I select with mssql_select_db().
If I try to connect like this:
$connect = mssql_connect('DSN_NAME', 'username', 'password');
where DSN_NAME matches a datasource specified in my freetds.conf file then I get an error and unable to connect to server: DSN_NAME which tells me that PHP isn't correctly seeing the path to my freetds.conf file.
However, if before my call I add:
putenv("FREETDSCONF=/opt/local/etc/freetds/freetds.conf");
then everything works as expected. This tells me that my freetds.conf file is formatted correctly.
I've searched all over about how to find the path that PHP thinks the freetds.conf file is in, but I can't find that.
Lastly, there are some reasons I don't want to use the IP address directly in my connection as well as why I don't want to be forced to use the putenv() method to specify the directory.
Any ideas?
Thank you.
When I installed FreeTDS I originally used MacPorts. I believe that this gave me some conflicts for where freetds.conf should have been. And even though the path for freetds.conf when running tsql -C was the actual path that I was attempting to use, when I compiled the mssql.so extension with that path PHP wouldn't recognize it.
The solution is to forget MacPorts for FreeTDS and just install FreeTDS from source. Then install the mssql.so extension from the PHP source and make sure you're using the same version that is on your system (mine was 5.3.13 under OS X Mountain Lion).
If you follow the instructions at this blog exactly you shouldn't have any issues.
A couple of final things:
I am NOT running MAMP even though the instructions mention it so it won't matter either way.
If you already did install FreeTDS via MacPorts, uninstall using: sudo port uninstall freetds +odbc and then sudo port uninstall unixODBC. Make sure you uninstall all instances of FreeTDS. If you have more than one, you'll get a notice when you run uninstall that you need to specify the version to uninstall.

Categories