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
Related
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).
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!
I am attempting to connect to a mysql database using the c9.io development environment. I have followed their documentation and have seen multiple links, 1, 2 and 3.
I verified the mysql service is running. I also verified the PDO extension was installed via phpinfo(). Here is my current code:
$ip = getenv("REMOTE_ADDR");
$port = '3306';
$user = "username";
$db = "c9";
try{
$con = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8",$user,"");
}
catch(Exception $e){
echo $e->getMessage();
}
I get the error Can't connect to MySQL server on '10.240.x.x' (111)
If i try localhost as host, I get the error Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I also followed a comment from the second link above: echo $IP in the terminal which returns 0.0.0.0
Any assistance appreciated.
You were on the right track. On https://docs.c9.io/setting_up_mysql.html it says use $IP for host. You can use getenv("IP") instead or use its value: 0.0.0.0. That should work.
Please try something like:
$dbname = 'c9';
$ip = getenv('IP');
$user = getenv('C9_USER');
mysql_connect($ip, $user, '') or die('Could not connect to mysql');
I am trying to connect to my local Database from the webserver but i get
Fatal error: Call to undefined function odbc_connect()
in -/-/-/7001238/web/s/sage2.php on line 15"
Any help on how to fix issue.
Here is the code i used to connect.
$odbc['dsn'] = "Sage50";
$odbc['user'] = "Peach";
$odbc['pass'] = "XXXX";
$mysql['host'] = "localhost";
$mysql['user'] = "root";
$mysql['pass'] = "";
$mysql['dbname'] = "sagetest";
$mysql['idfield'] = "id";
$debug=true;
// Step 1: Connect to the source ODBC and target mysql database
if ($debug) echo "Connect to " . $odbc['dsn'] . ' as ' . $odbc['user'] . "\n";
$conn = odbc_connect($odbc['dsn'], $odbc['user'], $odbc['pass']);
if (!$conn) {
die("Error connecting to the ODBC database: " . odbc_errormsg());
}
$myconn = mysql_connect($mysql['host'], $mysql['user'], $mysql['pass']);
if (!$myconn)
die("Error connecting to the MySQL database: " . $mysql_error());
if (!mysql_select_db($mysql['dbname'], $myconn)) die("Error selecting the database: " . mysql_error());
// Step 1.5: loop through each table with steps 2-7
$allTables = odbc_tables($conn);
$tablesArray = array();
while (odbc_fetch_row($allTables)) {
if (odbc_result($allTables, "TABLE_TYPE") == "TABLE") {
$tablesArray[] = odbc_result($allTables, "TABLE_NAME");
}
}
Thank you for your time!
First: This error happens because you don't have the ODBC PHP extension installed.
Check http://php.net/manual/en/odbc.installation.php too.
In debian distros you can solve this with a apt-get install php5-odbc, but you can check this also with your hosting provider.
When you see a Call to undefined function you always must check the php.net to be sure about the name of function, or the extension is not loaded.
PS 1: I think you're trying to compare/transfer data between two databases, right?
PS 2: Make sure your server can reach the ODBC address. The webserver is not your dev machine, so localhost is not the real localhost ;)
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?