PHP Connection to DB2 - php

I am trying to connect a database from php script.
<?php
$database = '****';
$user = '*****';
$password = '******';
$hostname = '********';
$port = 50000;
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');
if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>
I am geting the following error.
Call to undefined function db2_connect() in /home/s1.php on line 10
Can somebody Help me out how to resolve the following.

I think, you need to install DB2 extension.
Here is the link
http://php.net/manual/en/ibm-db2.installation.php

In addition to installing the db2 extension through PECL, you will need development header files and libraries downloaded on the system before running pecl install.
Here is a shell script that creates 3 files:
Dockerfile
docker-compose.yml
html/index.php
Obviously, please read script before copy/pasting to ensure you're comfortable
with what it does, but in short, it uses cat and the heredoc syntax to output
text into files:
#! /bin/sh
cat << 'EOF' > docker-compose.yml
version: '3'
services:
odb-web:
build: .
ports:
- 3030:80
volumes:
- ./html:/var/www/html
mydb2:
image: ibmcom/db2
ports:
- 50000:50000
volumes:
- ./data:/database
environment:
LICENSE: accept
DB2INST1_PASSWORD: ChangeMe!
DBNAME: testdb
privileged: true
EOF
cat << 'EOF' > Dockerfile
FROM php:7.3-apache
# To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system.
# DB2 does not install these by default, so you may have to return to your DB2 installer and add this option.
# The header files are included with the DB2 Application Development Client freely available for download from
# the IBM DB2 Universal Database » support site: https://www.ibm.com/developerworks/downloads/im/db2express/index.html
# https://github.com/php/pecl-database-ibm_db2
# Download linuxx64_odbc_cli.tar.gz from https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/
## add header files and libraries
RUN mkdir -p /opt/ibm/ && curl https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz | tar -xz -C /opt/ibm/
# if you prefer to keep the file locally, download it and use:
# ADD odbc_cli/linuxx64_odbc_cli.tar.gz /opt/ibm/
## set env vars needed for PECL install
ENV IBM_DB_HOME=/opt/ibm/clidriver
ENV LD_LIBRARY_PATH=/opt/ibm/clidriver/lib
## install ibm_db2 drivers
RUN pecl install ibm_db2
RUN echo "extension=ibm_db2.so" > /usr/local/etc/php/conf.d/ibm_db2.ini
EOF
mkdir html && cat << 'EOF' > html/index.php
<?php
$database = 'testdb';
$user = 'db2inst1';
$password = 'ChangeMe!';
$hostname = 'host.docker.internal';
$port = 50000;
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');
if ($conn) {
echo "Connection succeeded.\n";
db2_close($conn);
}
else {
echo "Connection failed.\n";
}
?>
EOF
upon running this script (or if on windows, copy pasting the file contents manually), you will have 3 files, and can run docker-compose up -d to build a php 7.3 image with apache and then it brings up two containers -- the php apache server and the ibm db2 database.
Browsing to http://localhost:3030 you should see "Connection succeeded".
You can modify the html/index.php file as desired and refresh the page to test things out.

just download a suitable version from PECL

Related

mamp pro, php 7.3.8 and remote mssql server

i use mamp pro on mac (catalina) and try to connect to remote mssql server.
in order to work with mssql i installed on the relevant php mamp folder:
brew install msodbcsql17 mssql-tools
pecl install sqlsrv pdo_sqlsrv
than i updated the php.ini file
extension=sqlsrv.so
extension=pdo_sqlsrv.so
when i try to run (of course with the correct credentails and server name)
$db = new PDO("sqlsrv:Server=MY.SERVER;Database=MYDBNAME", "MYUSER", "MYPASS");
i get this error:
Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712
what am i missing?
The PHP-PDO driver wants to access MS-SQL-server via the ODBC driver of SQL-server.
You need to install the odbc driver by doing
brew install msodbcsql17 mssql-tools
Afterwards, you need to enable TCP connections on sql-server, add a login, add the login to the correct role, and then you need to open port 1433, so TCP connections to SQL-server can work (unless you have both PHP and the sql-server run on the same machine).
And you might have to install UnixODBC:
brew install unixodbc
Also, you might have to add php_odbc to extensions
extension=php_odbc.dll
and php-fpm uses another ini file than php-cli/php-cgi.
On ubuntu, the PHP-fpm ini file is in
/etc/php/7.2/fpm/php.ini
while the other is in
/etc/php/7.2/cli/php.ini
Another alternative, if you can't get ODBC to work, is to use PDO_DBLIB, which uses FreeTDS instead of ODBC. That might be better anyway.
sudo pecl install pdo_dblib
However, that restricts you to php > 5.03 < 6.0.0.
Maybe you can compile it from source.
Mine works on Linux, all I had to do was:
sudo apt-get install php-fpm php-dev php-pear
sudo pecl install sqlsrv pdo_sqlsrv
(msodbcsql17 and mssql-tools I already had installed)
add the lines
extension=sqlsrv.so
extension=pdo_sqlsrv.so
into both ini files, and done.
Then I executed the connection-test-sample
php ./test.php
(i have port 2017, on docker), and it worked:
<?php
$serverName = "localhost,2017";
$connectionOptions = array(
"database" => "MY_DB_NAME",
"uid" => "sa",
"pwd" => "TOP_SECRET"
);
// Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(formatErrors(sqlsrv_errors()));
}
// Select Query
$tsql = "SELECT ##Version AS SQL_VERSION";
// Executes the query
$stmt = sqlsrv_query($conn, $tsql);
// Error handling
if ($stmt === false) {
die(formatErrors(sqlsrv_errors()));
}
?>
<h1> Results : </h1>
<?php
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['SQL_VERSION'] . PHP_EOL;
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
function formatErrors($errors)
{
// Display errors
echo "Error information: <br/>";
foreach ($errors as $error) {
echo "SQLSTATE: ". $error['SQLSTATE'] . "<br/>";
echo "Code: ". $error['code'] . "<br/>";
echo "Message: ". $error['message'] . "<br/>";
}
}
?>
<h1>Results: </h1>
Microsoft SQL Server 2017 (RTM-CU16) (KB4508218) - 14.0.3223.3 (X64)
Jul 22 2019 17:43:08 Copyright (c) Microsoft Corporation
Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)
I get a funny warning, though:
PHP Warning: PHP Startup: Unable to load dynamic library
'/usr/lib64/php/modules/pdo_sqlsrv.so' -
/usr/lib64/php/modules/pdo_sqlsrv.so: undefined symbol:
php_pdo_register_driver in Unknown on line 0
If I remove
extension=pdo_sqlsrv.so
then it works, without warning.
Note:
Just fixed the crap.
If you run php --ini, it will list you all the ini-files php loads.
The correct location (on Linux) to put these two lines is
/etc/php/7.2/mods-available/pdo.ini
The above warning occurs if extension=pdo_sqlsrv.so is loaded before extension=pdo.so. Also, that way, you only need to set the extension ONCE, and it's done for both php-cli and php-fpm. The mods-available are then (already) symlinked into php-fpm and php-cli.
You might have the same problem on Mac.
To make sure there are no permission issues, create a test user that is sysadmin:
-- The available default languages:
-- SELECT * FROM sys.syslanguages AS sysl
CREATE LOGIN [WebServicesTest] WITH PASSWORD = 'TOP_SECRET'
,CHECK_EXPIRATION = off
,CHECK_POLICY = off
,DEFAULT_LANGUAGE = us_english;
EXEC master..sp_addsrvrolemember [WebServicesTest], N'sysadmin';
To test if the connection is actually working with the user, you can use AzureDataStudio.
Beware:
If your system uses OpenSSL 1.1 (e.g. Ubuntu 19.04), you need to download the insiders-build.
TDS-based providers (freeTDS/ODBC) need TCP open, even if you work on localhost.
if anyone needs the answer
turned out need to install one more thing:
brew install msodbcsql#13.1.9.2 mssql-tools#14.0.6.0

PHP PDO + PostgreSQL Connection Error: Could not find Driver

There are a few similar questions that I have read through and followed the advice but to no end, and only being fairly new to this, I figured now was a good time to stop 'trying' things in case I break anything any further.
I'm receiving the following error when trying to connect to my database via PDO:
Connection error: could not find driver
1. I've ensured that Apache is linked to my homebrew PHP.
$ which php
/usr/local/bin/php
2. Have uncommented the following in php.ini
extension=php_pdo_pgsql.dll
The pdo_pgsql module shows up in php_info
3. My database connection is:
<?php
class Database
{
public $conn;
public function getConnection()
{
try {
$this->conn = new PDO("postgres://$user:$pass#$host:$port/$db_name");
print_r($this->conn);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->exec("set names utf8");
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
exit();
}
return $this->conn;
}
}
I've triple checked these details and they are correct (albeit ommitted). I can connect with the same URI via IntelliJ's Database connection Wizard
4. I’ve edited /usr/local/var/postgres/postgresql.conf to include:
#listen_addresses = '*'
I'm still not having any luck and am looking at some guidance in this head scratcher.
As I see you are using Linux, but tried enable .dll library which is used for Windows machines. It makes sense to comment this line.
Make sure that you have pdo_pgsql module enabled:
# php -m | grep pdo_pgsql
pdo_pgsql
Install it if it is not
# yum install php-pgsql
Here is steps that I did to make PHP+PostgreSQL work on my clean CentOS 7 install:
Install PostgreSQL (but I think you already have this installed and
configured)
# yum install postgresql-server postgresql-contrib
Updated config /var/lib/pgsql/data/pg_hba.conf, changed from ident to md5
host all all 127.0.0.1/32 ident
host all all ::1/128 ident
After
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
Restart postgresql service
# service postgresql restart
Install PHP and PDO connector
# yum install php php-pgsql
Here is an example of PHP script I used to test connection:
<?php
// Configure DB Parameters
$host = "localhost";
$dbname = "masterdb";
$dbuser = "automation";
$userpass = "fGmK4hvDZPB6fr6c";
$dsn = "pgsql:host=$host;port=5432;dbname=$dbname;user=$dbuser;password=$userpass";
try{
// create a PostgreSQL database connection
$conn = new PDO($dsn);
// display a message if connected to the PostgreSQL successfully
if($conn){
echo "Connected to the $dbname database successfully!";
echo "\n";
}
}catch (PDOException $e){
// report error message
echo $e->getMessage();
}
And the output:
# php pdo_test.php
Connected to the masterdb database successfully!

Docker with PHP and MySql - $servername Error [duplicate]

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(41 answers)
Closed 5 years ago.
I have a project developed with PHP and MySql.
When I Use the connection to DB I set the connection as a follow:
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
/* -------------------------------- CONNESSIONE -------------------------------------- */
$servername = "localhosto";
$username_db = "xxxxxx";
$password_db = "yyyyyy";
$db = "zzzzzz";
try {
$conn = new PDO("mysql:host=$servername;dbname=$db", $username_db, $password_db);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully<br/><br/>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage()."<br/><br/>";
}
the project run correctly and connect to MySql without problems.
Next step I was created a Docker Image with a follow docker file:
FROM php:7.0-apache
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq-dev \
&& docker-php-ext-install mysqli pdo_pgsql pdo_mysql
COPY / /var/www/html
EXPOSE 80
I have create the image and container:
docker build -t mysoftware C:\Users\mysoftware
docker run -d -p 5000:80 mysoftware
but the Php application don't connect to MySql.
I need to change the connection with the name of server:
$servername = "SERVER_NAME";
Why I have an error if the app run correcly without container ??
When running inside the container, localhost will not resolve to the host machine, rather it will refer to the container IP address.
You need to connect to the host machine from within the container. For that check: From inside of a Docker container, how do I connect to the localhost of the machine?
(Assuming *nix) Once you have the mysql docker container running...
docker ps
and find the name of the mysql container that is running. Then to find the IP address...
docker inspect <name_of_container> | grep IPAddress
Then use this IP address for the server to connect to.

Using PHP MSSQL PDO with Plesk

My current Website Control Panel is PLESK Parallels, and i'm trying to use PDO MSSQL on my website.
I've searched the internet and i'm aware that the PDO dll needs to be in my php.ini file and such, but I keep reading different ways to do it all the time, using commands like YUM and i'm getting confused.
Can someone possibly, in plain, simple black and white instructions, explain the process so I can simply run code like this
try {
$hostname = "myhostname";
$port = myportnumber;
$dbname = "databasename";
$username = "user";
$pw = "password";
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
When I load my page where this command is located i get the error message
'Failed to get DB handle: could not find driver'
Thanks
Example of installing pdo_dblib on CentOS-like OS for Plesk PHP 5.6:
# yum install plesk-php56-devel
# /opt/plesk/php/5.6/bin/pecl download pdo_dblib
# tar -xzf PDO_DBLIB-1.0.tgz
# cd PDO_DBLIB-1.0/
# /opt/plesk/php/5.6/bin/phpize
# ./configure --with-php-config=/opt/plesk/php/5.6/bin/php-config --with-pdo-dblib=./freetds
# vim pdo_dblib.c
On line #37 replace:
function_entry pdo_dblib_functions[] = {
with:
zend_function_entry pdo_dblib_functions[] = {
Save file and:
# make
# make install
you should see something like
Installing shared extensions: /opt/plesk/php/5.6/lib64/php/modules/
Enable extension:
# echo "extension=pdo_dblib.so" >> /opt/plesk/php/5.6/etc/php.d/pdo_dblib.ini
Verify:
# /opt/plesk/php/5.6/bin/php -m | grep pdo_dblib
pdo_dblib
Now sites in Plesk with PHP handler 5.6 will work with:
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
Pay attention for :
PHP DBlib PDO Issue
How to connect MSSQL from PHP 7, Plesk 12.5 installed on CentOS 7
PHP PDO works in OOPS .
Hence in PHP PDO first you must create a database handler using PDO class which is already defined in PHP Library. which will work as object for your database queries.
When you connect your database using PDO Class than you are ready to play with your queries with the database handler which you got during PDO connection.
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
Here $dbh will works as database handler object for MySQL Queries Operations.
I have a personal blog for PHP PDO here . Just go to reference and take a look how queries are working . Finally i would like to say it's very simple and secure.

Apache 2.4.7 on Ubuntu 14.04 will not connect to MSSQL through PHP 5.5

I am trying to connect to a remote MSSQL server using the platforms listed in the title. I have FreeTDS and all the relevant ODBC packages installed. Here is my freetds.conf:
# $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
; tds version = 4.2
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
; dump file = /tmp/freetds.log
; debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
[DEVSQL]
host = x.x.x.x
instance = DEVSQL
tds version = 8.0
Here is my odbc.ini:
[ODBC Data Sources]
DEVSQL = FreeTDS Connection Server
[DEVSQL]
Description = MSSQL Server
Driver = freetds
ServerName = DEVSQL
Database = test
TDS_Version = 8.0
Here is my PHP code:
<?php
$dbname = "test";
$servername = "DEVSQL";
$username = "myuser";
$password = "mypassword";
try{
$db = new PDO('odbc:Driver=FreeTDS; Server='.$servername.'; Database='.$dbname.'; UID='.$username.'; PWD='.$password.';');
Database='.$dbname.'; UID='.$username.'; PWD='.$password.';');
}
catch(PDOException $exception){
die("Unable to open database.<br />Error message:<br /><br />$exception.");
}
echo '<h1>Successfully connected!</h1>';
?>
I am able to connect just fine using the following commands in the terminal:
TDSVER=8.0 tsql -S devsql -U myuser -P mypassword
as well as:
isql -v devsql myuser mypassword
But when I browse to index.php in FireFox I get the following error:
exception 'PDOException' with message 'SQLSTATE[08001]
SQLDriverConnect: 0 [unixODBC][FreeTDS][SQL Server]Unable to connect
to data source' in /var/www/html/index.php:16 Stack trace: #0
/var/www/html/index.php(16): PDO->__construct('odbc:Driver=Fre...') #1
{main}.
Any help much appreciated! Alos, if anyone has a better way to connect to sql server from a linux box using php, I'm all ears. Thanks again!
EDIT: I forgot to mention: Ubuntu and Apache are running inside a VM instance on a Win7 host. The Win7 environment on that same machine is where the SQL server is running. I'm not sure if that's relevant since they are communicating just fine, but thought I'd throw it out there.

Categories