I have a php file with a mssql connection, which works on windows.
Now I would like to run my php on linux.
I installed unixodbc and msodbcsql.
The server is running RedhatEnterprise 6 and php 5.4
I cant find any description how to connect to a mssql database with linux.
What else do I have to install and configure?
You can certainly connect directly to Microsoft SQL Server database from a Linux server, using PHP's PDO system and the dblib driver.
First, install the EPEL repository and then install the php-mssql package. Then use the following code to set up your connection:
$dbhost = "your.db.server";
$dbname = "yourdbname";
$dbuser = "yourdbuser";
$dbpass = "yourdbpassword";
$db = new PDO("dblib:$dbhost;dbname=$dbname", $dbuser, $dbpass);
foreach ($db->query("select * from mytable") as $row) {
echo "{$row['field1]'}<br/>";
}
Additional StackOverflow resources on this topic include:
Connecting to mssql using pdo through php and linux
pdo dblib on centos 6.x
I faced the same challenge very recently, and after a lot of head scratching ultimately, I decided to go about things a little differently, as follows.
I set up a Windows machine (it could be a virtual machine) running PHP and Apache to handle the MSSQL requests from the Linux box.
The PHP on Linux uses a CURL command to send a request to Windows, and the response contains the data (compressed).
A little off-beat perhaps, but working well.
You need to have the modules sqlsrv and pdo_sqlsrv active.
sudo apt-get install php-fpm pcp-cli php-dev php-pear
sudo pecl install sqlsrv pdo_sqlsrv
The correct location (on Linux) to put these two lines is in /etc/php/<version>/mods-available/pdo.ini
there, add
extension=sqlsrv.so
extension=pdo_sqlsrv.so
Then restart/reload php-fpm or the computer.
Then run ./test.php (where port 2017 is the SQL-server-port)
#!/usr/bin/php
<?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/>";
}
}
?>
And to query the db with SQL-server pdo:
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try
{
$dbh = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
}
catch (PDOException $e)
{
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
$stmt = $dbh->prepare("SELECT name FROM master.sys.databases WHERE name = db_name()");
$stmt->execute();
while ($row = $stmt->fetch()) {
print_r($row);
}
unset($dbh); unset($stmt);
Related
I can not recognize the SQL Server command in XAMPP 1.8.1 and PHP 5.4.7, this code had already used it and it worked before but now it doesn't.
I have already tried to put the php_mssql.dll dll and still don't recognize the command:
$con = mssql_connect('187.164.1.2/base','pag','123') or die('Could not connect to the server!');
mssql_select_db('aguacom') or die('Could not select a database.');
I expected it to connect to the other server's database.
You are trying to connect to MS SQL Server using MSSQL PHP extension (mssql_ functions), but this extension is not available anymore on Windows with PHP 5.3 and removed in PHP 7.0.0.
What you can do is to install PHP Driver for SQL Server (sqlsrv_ functions). You need to download:
The appropriate version of this driver - for PHP 5.4 you need version 3.2 (32-bit or 64-bit depending on the PHP version)
The appropriate ODBC driver.
Note, that MSSQL PHP extension (php_mssql.dll) and PHP Driver for SQL Server (php_sqlsrv_54_ts.dll) are two different PHP extensions.
Example using mssql_ functions:
<?php
$server = "187.164.1.2/base";
$username = "pag";
$password = "123";
$database = "aguacom";
$conn = mssql_connect($server, $username, $password);
if ($conn === false) {
echo "Unable to connect. ".mssql_get_last_message()."</br>";
exit;
} else {
echo "Connected.</br>";
}
mssql_select_db($database, $conn);
// ...
mssql_close($conn);
?>
Example using sqlsrv_ functions:
<?php
$server = "187.164.1.2/base";
$username = "pag";
$password = "123";
$database = "aguacom";
$connectionInfo = array(
"UID" => $username,
"PWD" => $password,
"Database" => $database
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) {
echo "Unable to connect. ".print_r(sqlsrv_errors(), true)."</br>";
exit;
} else {
echo "Connected.</br>";
}
// ...
sqlsrv_close($conn);
?>
you should enable mssql in xampp
things you need [download these files]: https://www.microsoft.com/en-us/download/details.aspx?id=20098
Add downloaded files in php.ini like this way
extension=php_sqlsrv_56_ts.dll
extension=php_pdo_sqlsrv_56_ts.dll
restart apache and then check
<?php
echo "<pre>";
print_r(PDO::getAvailableDrivers()); ?>
credits goes to rray
I have problem to connect to SQL server. I did all the steps from here and I already changed the php.ini configuration file:
;On windows:
extension_dir = "D:\xampp\php\ext"
But I still can't connect, my PHP Version is 7.2.11. I tried with mssql_connect() and sqlsrv_connect():
This is my attempt:
<?php
$servername = "1111";
$username = "user";
$password = "123";
$dbname = "DEV";
$connection = mssql_connect($servername, $username, $password);
if (!$connection) { die('Not connected : ' . mssql_get_last_message());}
$db_selected = mssql_select_db($dbname, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mssql_get_last_message());
} else{
echo "success";}
?>
MSSQL extension for PHP (mssql_ functions) and PHP Driver for SQL Server (sqlsrv_ functions) are two different extensions for PHP.
MSSQL extension is not available anymore on Windows with PHP 5.3 or later, so you need to install PHP Driver for SQL Server. You need to download appropriate version of this driver. For PHP 7.2 - version 5.2 or 5.3 (32-bit or 64-bit also depends on PHP version).
Also download and install an appropriate ODBC driver.
Check the configuration with <?php phpinfo();?>. There should be a section with name pdo_sqlsrv (if you use PDO) and/or sqlsrv (without PDO).
Example:
<?php
$server = '1111';
$database = 'DEV';
$uid = 'user';
$pwd = '123';
# SQL Server authentication
#$cinfo = array(
# "Database" => $database,
# "UID" => $uid,
# "PWD" => $pwd
#);
# Windows authentication
$cinfo = array(
"Database" => $database
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
} else {
echo "success";
}
sqlsrv_close($conn);
?>
I am trying to connect my SQL server db instance to my PHP application in elastic beanstalk.It is giving me an error "driver 1 not found". I am using following code to connect my db instance inside same environment.
<?php
$dbhost = $_SERVER;
$dbport = $_SERVER;
$dbname = $_SERVER;
$charset = 'utf8' ;
$dsn = "sqlsrvl:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER;
$password = $_SERVER;
$pdo = new PDO($dsn, $username, $password);
?>
AWS developer guide mentions to install a driver for PDO_SQLSRV. I tried installing driver by using .ebextensions folder in my application root directory with a .config file to install the package.
packages:
yum:
php56-mssql: []
but this result in degrading my environment health to server.
I used this links as my reference
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP.rds.html
http://techqa.info/programming/question/35984661/how-to-connect-aws-elb-to-rds-running-ms-sql
Is there any other way to install pdo_sqlsrv driver and extension in elastic beanstalk php application ?
I am new to aws .Please help me to resolve this problem it would bee appreciated.
Addition info:
My platform: 64bit Amazon Linux 2016.09 v2.3.3 running PHP 7.0
After trying multiple answers, I figured out the solution for this issue.
The problem was PHP 7.0 version, for which I had to use package
commands:
00install_mssql:
command: yum install -y php70-mssql
Adding the above code in my application root directory .ebextensions/any.config file
In my case, the amazon document did not helped me because it mentions PDO_SQLSRV driver to be install but they do not support that driver instead I had to use PDO_DBLIB driver below is an example of it.
$dbhost = 'XXXXXXXXXXX.XXXXXXXXXXXXXXX.amazonaws.com:1433';
$dbname = 'dbname';
$charset = 'utf8' ;
$username = 'usernam';
$password = 'password';
$pdo = new PDO("dblib:host=$dbhost;Database=$dbname", $username, $password);
$pdo->setAttribute( PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL);
$tsql ="Select InvID, Number, ProfileNum, PName, InvDate, Des
FROM dbname.dbo
WHERE ProfileNum ='" . $client_no . "'
AND InvDate BETWEEN '". $inv_from_date."' AND '".$inv_to_date."'
ORDER BY InvID";
ini_set('max_execution_time', 300);
/* Execute the query.*/
$stmt = $pdo->query( $tsql );
if ( $stmt->execute() )
{ echo "Statement executed.<br>\\n"; }
else
{ echo "Error in statement execution.\\n";
die( print_r(DBLib_error(), true)); }
$title = $stmt->fetchColumn(3);
print "Client Number :" . $client_no . " <br />";
print" Client Name    :" . $title. ""; // Displaying Client Information
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'm trying to hack together a script to connect to a remote oracle database and execute a simple query
Through extensive searches I found the following script:
<?
$tns = "
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = bogus.com.au)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = myDB )
)
)
";
$pdo_string = 'oci:dbname='.$tns;
try {
$dbh = new PDO($pdo_string, 'test', 'fake');
} catch (PDOException $e) {
echo "Failed to obtain database handle: " . $e->getMessage();
exit;
}
$query = "SELECT * FROM someTable";
$stmt = $dbh->prepare($query);
if ($stmt->execute()) {
echo "<h4>$query</h4>";
echo "<pre>";
while ($row = $stmt->fetch()) {
print_r($row);
}
echo "</pre>";
}
?>
However I'm getting the error could not find driver. So I did:
foreach(PDO::getAvailableDrivers() as $driver)
echo $driver, '<br>';
Which returned:
mysql
odbc
sqlite
That tells me that I do have the driver installed, yes?
What am I doing wrong? (Admittedly I have little to no knowledge of PHP with Oracle databases so maybe I'm missing the blatantly obvious..)
You have to install Oracle adapter in PDO:
http://php.net/manual/en/ref.pdo-oci.php
You have to configure your server to enable the PDO_OCI extension.
Go to php.ini and find the line extension=php_pdo_oci.dll and remove the comma ; from its start then restart your apache service.