Connecting to sql server data with PHP on ubuntu - php

When trying to connect to my mssql database, I get the error
"SQLSTATE[01002] Adaptive Server connection failed (severity 9)"
Below is the php code I'm running
<?php
try {
$hostname = "hostname.database.windows.net";
$port = 1433;
$dbname = "database-dev";
$username = "dbuser";
$pw = "dbpassword";
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$stmt = $dbh->prepare("select name from master..sysdatabases where name = db_name()");
$stmt->execute();
while ($row = $stmt->fetch()) {
print_r($row);
}
unset($dbh); unset($stmt);
?>
And below is my odbc.ini, odbcinst.ini and freetds.conf, you can see my phpinfo() here ("http://wingedw.com/matiks/connect.php") the driver is set to freetds and the pdo and pdo_dlib modules have been added to php 5, any clues as to why im getting error, im sure the credentials are right.
odbc.ini
[MSSQLServer]
Driver = FreeTDS
Description = Any description
Trace = No
Server = servername
Port = 1433
Database = dbname
wTDS_Verison = 7.1
odbcinst.ini
[FreeTDS]
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
freetds.conf
[global]
# TDS protocol version
; tds version = 7.1
# 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 = 100
; connect timeout = 100
# 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
# A typical Sybase server
[egServer50]
host = symachine.domain.com
port = 5000
tds version = 7.1
# A typical Microsoft server
[MSSQLServer]
host = servername
port = 1433
tds version = 7.1

Turns out everything was configured correctly, the issue was using dblib over odbc, see code below.
try {
$hostname = "hostname.database.windows.net";
$port = 1433;
$dbName = "databasename";
$dbuser = "dbuser#hostname";
$dbpass = "password";
$dbh = new PDO('odbc:DRIVER=FreeTDS;SERVERNAME=mssql;DATABASE=' . $dbName,
$dbuser, $dbpass);
//echo "COnnected";
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}

2021 - BACK TO THE FUTURE:
I know that this post is old, but my reply can point a desperate soul in the right direction:
You are using odbc and the command "isql" works just fine
You are using FreeTDS and the command "tsql" works just fine
Trouble is running the php scripts that have calls to odbc via FreeTDS -> keeps giving errors
Kindly read:
https://www.linuxquestions.org/questions/blog/tix-592494/freettds-libiodbc-iodbc-php-7-4-21-on-slackware-current-5-13-5-38621/
Cheers happy souls!

Related

"could not find driver" error for "new PDO()" command, PHP 7.0.25

I'm not able to use "new PDO()" as I keep getting this error message, "could not find driver." I'm using hostgator, and have worked extensively with them, to no avail.
I've updated my PHP version to 7.0.25, checked the default php.ini settings (hostgator uses a cookie-cutter default php.ini file for all their customers... unless you create your own custom php.ini file, in which case the custom version overrides). I've looked over my phpinfo() results, and everything looks good (unless I'm missing something). I've included my script and snippets of my php.ini file settings and phpinfo() results.
PHP.ini file settings:
[Pdo]
; Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off"
; http://php.net/pdo-odbc.connection-pooling
;pdo_odbc.connection_pooling=strict
;pdo_odbc.db2_instance_name
[Pdo_mysql]
; If mysqlnd is used: Number of cache slots for the internal result set cache
; http://php.net/pdo_mysql.cache_size
pdo_mysql.cache_size = 2000
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
pdo_mysql.default_socket=
phpinfo() results:
PDO drivers: mysql, sqlite
Client API version: 5.6.41-84.1
Directive: pdo_mysql.default_socket
Local value: /var/lib/mysql/mysql.sock
Master value: /var/lib/mysql/mysql.sock
<?php
$host = "localhost";
$user = "ABC";
$pw = "123";
$dbName = "XYZ";
$dsn = 'msql:host=' . $host . ';dbname=' . $dbName;
$pdo = new PDO($dsn,$user,$pw); // this is the line that the error refers to
$eml = $_POST['data'];
$newPassword = $_POST['data1'];
$cnewPassword = $_POST['data2'];
$query = $pdo->query("SELECT * FROM accounts WHERE email = $eml") or die(mysql_error());
$row = $query->fetch(PDO::FETCH_ASSOC);
if($row > 0) {
echo "GOOD";
} else {
echo "BAD";
};
?>
I should get an echo "GOOD", but all I keep getting is the "could not find driver" error. One important thing to note; I did notice that the PHP version that hostgator used to upgrade was a NON THREAD SAFETY version... hostgator uses APACHE servers, and I've learned that only the THREAD SAFE versions will work with APACHE servers. This could be the issue, but not 100 percent sure. Any input/advice would greatly be appreciated!
Basic syntax error:
// $dsn = 'msql:host=' . $host . ';dbname=' . $dbName;<br>
$dsn = 'mysql:host=' . $host . ';dbname=' . $dbName;<br>
(msql instead of mysql).

Connecting from VM to MySQL

I'm having trouble connecting to a MySQL database on my host OS (Win 7) from my Oracle VirtualBox running Ubuntu. I wrote this php code in order to connect but I keep receiving an error connecting:
<?php
$dsn = 'mysql:host=192.168.1.9;dbname=finance';
$db_username = 'sdb_user';
$db_password = 'password';
try {
$db = new PDO($dsn, $db_username, $db_password);
}catch (PDOException $e) {
$error_message = $e->getMessage();
include('../errors/database_error.php');
exit();
}
$query = 'SELECT * FROM books';
$books = $db->query($query);
foreach ($books as $book) {
echo $book['title'];
}
?>
I know the code works, because I can get it to run from my Windows 7 host OS using localhost instead of the IP address, and I know that both Linux on VirtualBox and Windows 7 are on the same subnet because I can successfully ping the other from each side.
I'm fairly certain that I opened port 3306 correctly on the windows side also, but I have no idea how to check if that's the problem or not.
What else should I be doing to get the code to connect to the MySQL db?
EDIT: The problem was that the port was not open for remote connections. After I opened the port I got the error message stating I was not allowed to connect to the sql server. From there I created a new user on the Windows MySQL with the username "home" and password "home" and was able to connect to it using:
$ mysql -h 192.168.1.9 -u home -p
However, when I run my file, which now reads:
$dsn = 'mysql:host=192.168.1.9;dbname=finance';
$db_username = 'home';
$db_password = 'home';
I still get the 'database error'
Any suggestions?

MSSQL connection from PHP on FreeBSD

As an extension of my question: Remote connect to SQL Server Standard Edition from PHP/FreeBSD
I'm trying to get our FreeBSD/Apache/PHP server to be able to query our WinServer2003/SQL-Server-2000 box. Please note that this is not for a public system, only for a internal reporting function - so performance is not the key at this point.
The initial question helped me prepare the MSSQL server for connection, and is now getting some kind of response from it. However I haven't got a successful connection to it.
I have tried PDO_dblib, mssql (FreeTDS) - haven't tried ODBC. I would prefer if I could get PDO to work, so that's what I'm aiming at here - and it's also the most succesfull of the two I tried.
My PHP script that utilizes PDO:dblib
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
$servername = '192.168.1.51';
$port = '1433';
$serverdsn = $servername.':'.$port;
$username = 'webserver';
$password = '123456';
$dbname = 'oneServer_staging';
$sqlstatement = 'SELECT * FROM ordersp';
try
{
$pdo = new PDO ("dblib:host=".$serverdsn.";dbname=".$dbname,$username,$password);
}
catch (PDOException $e)
{
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
exit;
The result of this PDO:dblib script when running it in browser:
Failed to get DB handle: SQLSTATE[28000] Login incorrect. (severity 9)
And ind the MSSQL server's application log I find this:
EDIT after comment about FreeTDS
My PHP script that utilizes mssql_connect() / FreeTDS
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
$username = 'webserver';
$password = '123456';
$dbname = 'oneServer_staging';
$sqlstatement = 'SELECT * FROM ordersp';
$link = mssql_connect('MYMSDN', $username, $password);
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
The result of this mssql/FreeTDS script when running it in browser:
Warning: mssql_connect(): Unable to connect to server: MYMSDN in
/home/www/[..]/httpdocs/public/default/philip/oneserver-db-test.php
on line 17 Something went wrong while connecting to MSSQL
/usr/local/etc/freetds.conf
[global]
# TDS protocol version
tds version = 4.2
initial block size = 512
# uses some fixes required for some bugged MSSQL 7.0 server tha
# return invalid data to big endian clients
# NOTE TDS version 7.0 or 8.0 should be used instead
; swap broken dates = no
; swap broken money = no
# 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.
# (Microsoft servers sometimes pretend TEXT columns are
# 4 GB wide!) If you have this problem, try setting
# 'text size' to a more reasonable limit
text size = 64512
# A typical Microsoft SQL Server 2000 configuration
[MYMSDN]
host = 192.168.1.51
port = 1433
tds version = 8.0
client charset = UTF-8
The file /tmp/freetds.log shows nothing when executing the script, however if i use # tsql -C command, it's updated.
Does the following lines of code work?
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
$username = 'webserver';
$password = '123456';
$dbname = 'oneServer_staging';
$servername = '192.168.1.51';
if (!$link = mssql_connect($servername, $username, $password)) {
exit('Error: Could not make a database connection using ' . $username . '#' . $servername);
}
if (!mssql_select_db($dbname, $link)) {
exit('Error: Could not connect to database ' . $dbname);
}
?>
Do you need this line in your freetds.conf file? Are you sure both sides are using UTF-8?
client charset = UTF-8
Here's the code I use to connect PHP to MSSQL from Ubuntu machines to Windows SQL Server, I don't know if it will help you or not but this code is up and running successfully right now so I know it works in our environment...
PHP:
<?php
try{
$con = new PDO("dblib:dbname=$dbname;host=$servername", $username, $password);
}catch(PDOException $e){
echo 'Failed to connect to database: ' . $e->getMessage() . "\n";
exit;
}
?>
/etc/odbc.ini
# Define a connection to the MSSQL server.
# The Description can be whatever we want it to be.
# The Driver value must match what we have defined in /etc/odbcinst.ini
# The Database name must be the name of the database this connection will connect to.
# The ServerName is the name we defined in /etc/freetds/freetds.conf
# The TDS_Version should match what we defined in /etc/freetds/freetds.conf
[mssqldb]
Description = MSSQL Server
Driver = freetds
Database = MyDB
ServerName = mssqldb
TDS_Version = 8.0
/etc/odbcinst.ini
# Define where to find the driver for the Free TDS connections.
[freetds]
Description = MS SQL database access with Free TDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
/etc/freetds/freetds.conf
[global]
# 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
# Define a connection to the MSSQL server.
[mssqldb]
host = mssqldb
port = 1433
tds version = 8.0

How to establish a connection?

I am new to DB2.
$database = 'test';
$user = 'user1';
$password = 'pswd1';
$hostname = '10.250.10.10';
$port = 556;
$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 {
print($conn);
echo "Connection failed.";
die(db2_conn_errormsg());
}
all the values are correct. But connection have been failed. Plz advise me. and How to check in the PHPINFO(). whether the DB2 have been installed successfully or not.
I got the following error
Connection failed.[unixODBC][Driver Manager]Data source name not found, and no default driver specified SQLCODE=0
I'm not a PHP maven, but if you're using the ODBC driver, you probably need to catalogue the database in the ODBC driver manager. On Windows, search for ODBC in "Search Programs and Files". I'm not sure the equivalent on Linux

PDOException "could not find driver" on MAMP

I'm trying to work with PDO on my localhost. I'm running MAMP on OSX 10.7.4.
I've checked phpinfo(), and as far as I can see I should be fine.
I checked the php.ini to see that "extension=pdo_mysql.so" is in fact uncommented.
I read some were that I had to make the file PROJECTFOLDER/config/parameters.ini with the following content so i did, but with no luck. (Changed it to reflect my setup of cause)
database_driver = pdo_mysql
database_host = localhost
database_port =
database_name = databasename
database_user = msqlusername
database_password = mysqlpassword//if not make blank
mailer_transport = smtp
mailer_host = localhost
mailer_user =
mailer_password =
locale = en
secret = ThisTokenIsNotSoSecretChangeIt
Any ideas as to how I can get PDO up and running?
BTW I'm using the following code to make the connection:
try {
$host = 'localhost';
$dbname = 'ifjernsyn';
$user = 'root';
$pass = 'root';
# MS SQL Server and Sybase with PDO_DBLIB
$DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
# SQLite Database
$DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
So there is not mssql and sybase 's driver.
You need PDO_DBLIB to access Microsoft SQL Server and Sybase databases.

Categories