mamp pro, php 7.3.8 and remote mssql server - php

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

Related

How to connect sql server with php using xampp?

I am trying to connect my SQL server with PHP using Xampp. I have already uploaded dll files in the ext folder but I am unable to connect it.
My PHP version is 7.2.6.
Uploaded dll files are - php_pdo_sqlsrv_72_ts.dll, php_sqlsrv_72_ts.dll.
I have written this code to connect my SQL database with PHP-
<?php
$serverName = "INDO-SERV\SQLEXPRESS,1443";
$uid = "sa";
$pwd = "XXXXXX";
$databaseName = "web";
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>$databaseName);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.\n";
}
else
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_close( $conn);
?>
I am getting this error when I had tried this-
Fatal error: Uncaught Error: Call to undefined function
sqlsrv_connect() in C:\xampp\htdocs\biometric\db.php:7 Stack trace: #0
{main} thrown in C:\xampp\htdocs\biometric\db.php on line 7.
Anyone has an idea where I am doing wrong or how to connect with the database.
Installation of PHP Driver for SQL Server (sqlsrv and/or pdo_sqlsrv PHP extensions) can be done following the next steps:
Based on Microsoft PHP Drivers for SQL Server Support Matrix download appropriate version of this driver. In your case - version 5.2 or 5.3 (32-bit or 64-bit also depends on PHP version).
Download and install an appropriate ODBC driver - see System Requirements for the Microsoft Drivers for PHP for SQL Server
Load PHP Driver for SQL Server as PHP extension.
Restart Apache
Check the configuration with <?php phpinfo();?>. There should be a section with name pdo_sqlsrv (if you use PDO) and/or sqlsrv (without PDO).
my XAMPP version is 7.0.13
1- Download and Install "SQLSRV40.EXE" on this path:
D:\xampp\php\ext
2- Download and Install "msodbcsql.msi"
3- Edit file ":\xampp\php\php.ini" and add this extensions :
extension=php_sqlsrv_7_ts_x86.dll
extension=php_pdo_sqlsrv_7_ts_x86.dll
extension=php7ts.dll
4- restart xampp
Note: "SQLSRV40.EXE" Contain this extensions:
php_sqlsrv_7_ts_x86.dll , php_pdo_sqlsrv_7_ts_x86.dll , php7ts.dll
Download driver from:
https://download.microsoft.com/download/f/4/d/f4d95d48-74ae-4d72-a602-02145a5f29c8/SQLSRV510.ZIP
Unzip the files
Copy the dll files in C:\xampp\php\ext\
Open with your favourite editor the file php.ini located in C:\xampp\php\
Insert the extensions:
extension=pdo_sqlsrv_74_ts_x64
extension=sqlsrv_74_ts_x64
Restart Apache and PHP
For the new comers;
You can setup driver and integrate it as in this video explains so in a nutshell;
You should find drivers for php - sql server integration depending to your environment (versions) at links and download the driver that suits for your environment.
You should move the driver file (.dll for windows case) to php/ext folder.
You need to change php.ini as entering a new extension (for example extension=php_sqlsrv_7_ts.dll) by giving your exact file name you have moved to php/ext.
Restart your local server and you should see this extension in phpinfo(), if you can see it's there, you can connect to your db with your credentials and it's done.
Credits goes to creator of the video (applause) :)

How to install PECL HTTP extension for XAMPP?

I want to install the PHP PECL HTTP extension in my XAMPP environment (OS is Windows). I have attempted to add multiple variations of the php_http.dll extension into my ext directory, and added extension=php_http.dll to the php.ini file. Yet when I go to start the Apache service, it throws some sort of error.
It's pretty clear I'm doing something wrong, however I have no idea what. The last relevant question I could find was 5 years out of date. Does anybody have any idea how to install this?
You can try:
For pecl.
Look in xampp\php for the pecl.bat file
Open a command console window in this folder and issue the pecl.bat command and it will give a list of commands to use.
You also have to load raphf and propro:
http://windows.php.net/downloads/pecl/releases/raphf/1.0.4/
http://windows.php.net/downloads/pecl/snaps/propro/1.0.0/
... and iconv, hash and spl.
This post shows how to install XAMPP on Windows to run PHP applications that connect to a remote Oracle Database.
*
XAMPP is an open source package that contains Apache, PHP and many PHP
'extensions'. One of these extension is PHP OCI8 which connects to
Oracle Database.
*
To install XAMPP: D: drive.
Download "XAMPP for Windows" and follow the installer wizard. I installed into my D: drive.
Start the Apache server via the XAMPP control panel.
Visit http://localhost/dashboard/phpinfo.php via your browser to see the architecture and thread safety mode of the installed PHP. Please note this is the architecture of the installed PHP and not the architecture of your machine. It’s possible to run a x86 PHP on an x64 machine.
Oracle OCI8 is pre-installed in XAMPP but if you need a newer version you can download an updated OCI8 PECL package from pecl.php.net.
Pick an OCI8 release and select the DLL according to the architecture and thread safety mode. For example, if PHP is x86 and thread safety enabled, download "7.2 Thread Safe (TS) x86". Then replace "D:\xampp\php\ext\php_oci8_12c.dll" with the new "php_oci8_12c.dll" from the OCI8 PECL package.
Edit "D:\xampp\php\php.ini" and uncomment the line "extension=oci8_12c". Make sure "extension_dir" is set to the directory containing the PHP extension DLLs. For example,
extension=oci8_12c
extension_dir="D:\xampp\php\ext"
Download the Oracle Instant Client Basic package from OTN.
Select the correct architecture to align with PHP's. For Windows x86 download "instantclient-basic-nt-12.2.0.1.0.zip" from the Windows 32-bit page.
Extract the file in a directory such as "D:\Oracle". A subdirectory "D:\Oracle\instantclient_12_2" will be created.
Add this subdirectory to the PATH environment variable. You can update PATH in Control Panel -> System -> Advanced System Settings -> Advanced -> Environment Variables -> System Variables -> PATH. In my example I set it to "D:\Oracle\instantclient_12_2".
Restart the Apache server and check the phpinfo.php page again. It shows the OCI8 extension is loaded successfully.
If you also run PHP from a terminal window, make sure to close and reopen the terminal to get the updated PATH value.
To run your first OCI8 application, create a new file in the XAMPP document root "D:\xampp\htdocs\test.php". It should contain:
<?php
 
error_reporting(E_ALL);
ini_set('display_errors', 'On');
 
$username = "hr";                  // Use your username
$password = "welcome";             // and your password
$database = "localhost/orclpdb";   // and the connect string to connect to your database
 
$query = "select * from dual";
 
$c = oci_connect($username, $password, $database);
if (!$c) {
    $m = oci_error();
    trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
 
$s = oci_parse($c, $query);
if (!$s) {
    $m = oci_error($c);
    trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR);
}
$r = oci_execute($s);
if (!$r) {
    $m = oci_error($s);
    trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR);
}
 
echo "<table border='1'>\n";
$ncols = oci_num_fields($s);
echo "<tr>\n";
for ($i = 1; $i <= $ncols; ++$i) {
    $colname = oci_field_name($s, $i);
    echo "  <th><b>".htmlspecialchars($colname,ENT_QUOTES|ENT_SUBSTITUTE)."</b></th>\n";
}
echo "</tr>\n";
 
while (($row = oci_fetch_array($s, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "<td>";
        echo $item!==null?htmlspecialchars($item, ENT_QUOTES|ENT_SUBSTITUTE):" ";
        echo "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";
 
?>
You need to edit this file and set your database username, password and connect string. If you are using Oracle Database XE, then the connect string should be "localhost/XE".
The SQL query can also be changed. Currently it queries the special DUAL table, which every user has.
Load the test program in a browser using http://localhost/test.php. The output will be the single value "X" in the column called "DUMMY".
---- NOTE
Maybe this can help, but this issue is very complex in XAMPP. I have heard several reports about this problem in xampp, I advise testing VPS free for further study.
if you have any questions, post in the comments.
If something is incompatible or wrong, be sure to comment! thanks

MSSQL VIA FreeTDS, ODBC, and Cpanel Unknown host machine name (severity 2)

I have installed FreeTDS 0.91, ODBC, on a Cpanel server running Centos 6.5x64. Everything appears to be running fine and I can connect to the remote MSSQL 2012 server using:
/usr/local/freetds/bin/tsql -S sqlserver -U test -P mypassword
and succesfully execute queries in the database.
I can also connect through:
isql -v sqlserverdatasource test mypasswordhere
But for some reason /usr/local/freetds/bin/tsql -LH server.ip.here
returns no information or errors which doesn't make much sense when it is proven I can connect with the other methods above.
So now when running a test script from a cpanel account on the machine I get:
Unknown host machine name (severity 2)
Here is the test script:
//Database connection function.
function getConnection() {
try {
//$dbconnect = new PDO("sqlserver:Server=server.ip.here,1433;Database=dbname", "user", "password");
$dbconnect = new PDO("dblib:host=server.ip.here,1433;dbname=dbname", 'user', 'password');
} catch (PDOException $e) {
echo "CONNECTION ERROR.<br>Error message:<br><br>" . $e->getMessage();
die();
}
if (!$dbconnect) {
die('Cant connect to database. Please try again later!');
}
else{
echo "i'm in!";
return $dbconnect;
}
}
The first commented line is the old one using sqlserv which I found did not work at all from what i can tell because of the x64 OS. I have also tried with "" around user and pass as well as no marks at all.
php -m does show PDO and pdo-dblib.
Any ideas where I can look next?
Update: This was fixed. I missed in freetds.conf:
[global]
# TDS protocol version
tds version = 8.0
It was originally set to 4.5 instead of 8.
The fix for me was with three steps:
First, I edited /etc/freetds/freetds.conf and changed the tds version like this:
tds version = 8.0
The second step was not entering port number. The port was already 1433, and not specifying it fixed the exact same issue on my case.
Lastly, to connect properly, I had to restart networking as #user1054844 mentioned as this:
/etc/init.d/networking restart
After all these steps, I was able to connect and work with the SQL Server database.
You actually did not need ODBC at all since your connect script is using pdo_dblib not odbc. You can just install FreeTDS than enable pdo_dblib via the compile time flag in rawopts and rebuild via EasyApache. Of course cPanel specifics for this are a bit different.
I just did this for a friend and decided to document it since it is hard to find accurate clear information for FreeTds and pdo_dblib on cPanel.
Guide is here: FreeTDS And pDO_dblib On cPanel

PDO will not run since upgrading PHP to 5.4.22

I just recently upgraded my server's PHP version to 5.4.22, and now every script that uses PDO does not work.
An example of my PHP script which won't work:
<?php
$dsn = 'mysql:dbname=testDB;host=127.0.0.1';
$user = '[hidden]';
$password = '[hidden]';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
?>
When i run the script i get: Fatal error: Class 'PDO' not found, i get this same error for every script that creates a connection.
I ran a check on puTTY to check PDO was even there and it found this:
root#cpanel [~]# php -m | grep -i pdo
PDO
pdo_mysql
pdo_sqlite
My php.ini has
extension=pdo.so
extension=pdo_sqlite.so
; sqlite was removed by EasyApache v3.22.24 on Sat Dec 14 23:24:10 2013 (PHP v5.4.x incompatibility)
; extension=sqlite.so
extension=pdo_mysql.so
phpinfo(); in PHP file claims im on PHP Version 5.3.10
How ever in my terminal # php -v says PHP 5.4.22
So this had really confused me why i'm getting two versions.
Your question shows that you are checking the PHP version via the command line. But PHP via a web browser is going to use a module loaded into Apache which is a completely different thing. So check the output of phpinfo(); in a PHP script loaded via the web browser. Is PDO installed or shows as installed via that?
Wherever your Apache config files are look for the directory mods-available and the file php5.load. Under Ubuntu 12.04 it would be in this path:
/etc/apache2/mods-available/php5.load
And the contents should be:
LoadModule php5_module /usr/lib/apache2/modules/libphp5.so
Does the path in that file match where the newly compiled libphp5.so is installed?
Also, that LoadModule php5_module line could be a part of your main Apache configuration. Look around to find where that is set. And then just set the path of the new module to me wherever it’s actually installed.

How can I connect to Sql Server from a Mac with PHP PDO?

If you search Google for this question, you will find a lot of incorrect, misleading, and outdated information. Surprisingly, there isn't a solid answer on Stack Overflow, so we should change that.
I am using the Mac port installation of Apache and PHP. I have installed php5-mssql, and I can see mssql on my phpinfo() page.
But I don't see it listed under PDO.
PDO support enabled
PDO drivers dblib, mysql, odbc, pgsql
Is mssql not associated with PDO? Is there another driver that can be used on a Mac to connect to a SqlServer database using PDO? Seems like this is something that should be possible.
Does this help you?
http://blog.nguyenvq.com/2010/05/16/freetds-unixodbc-rodbc-r/
I use FreeTDS to connect to Microsoft SQL servers from a Linux server and it looks like the person in the link above has used FreeTDS to connect from a Mac.
Here is my /etc/freetds/freetds.conf file (the only part I added was at the very end for the XYZ server):
[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
# Define a connection to the MSSQL server.
[xyz]
host = xyz
port = 1433
tds version = 8.0
[Edit by the asker]
FreeTDS configuration is the first half of the answer. Once it's configured you should be able to run something like this from the command line and connect:
tsql -S xyz -U username -P password
Then you need to use dblib, not mssql, as the PDO driver:
$pdo = new PDO("dblib:host=$dbhost;dbname=$dbname",
"$dbuser","$dbpwd");
Where $dbhost is the name from the freetds.conf file
After looking at many threads, I've found that the best way to connect to MSSQL from Mac OS X with PHP 7 or older is to use dblib. (Just download the correct php version)
You can follow these instructions (ignoring the mssql.so extension) to connect very easily:
https://github.com/BellevueCollege/public-docs/blob/master/PHP/configure-mssql-pdodblib-mac.md
It worked perfect with OS X El Capitan, Bitnami with PHP 7.
Steps
1.- Install XCode
$ xcode-select ---install
2.- Install Homebrew
3.- Install autoconf using Homebrew.
$ brew install autoconf
4.- Install FreeTDS
$ brew install freetds
5.- Download your version of PHP Source and uncompress it.
6.- Build the PDO DBLIB extension (Example for PHP 5.5.14)
$ cd php-5.5.14/ext/pdo_dblib
$ phpize
$ ./configure --with-php-config=/usr/bin/php-config --with-pdo-dblib=/usr/local/
$ make
$ sudo cp modules/pdo_dblib.so /usr/lib/php/extensions/no-debug-non-zts-20121212
7.- Add the .so extensio to php.ini
extension=pdo_dblib.so
8.- Restart Apache
9.- Connect using the dblib dsn:
$pdo = new PDO("dblib:host=$dbhost;dbname=$dbname","$dbuser","$dbpwd");
dblib is the driver that need to be used with mssql on unix systems
No need for you to install anything else,
<?php
$dsn = 'dblib:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Thanks Esteban for the nice guide (https://stackoverflow.com/a/37707426) which succesfully helped me install the pdo_dblib driver.
However, I was having issues connecting to my Azure SQL database from OSX 10 with PHP (5.5) and FreeTDS using the provided dblib dsn. What finally fixed it for me was appending the Azure database (m53man42a) to my username.
My dblib PDO connection in PHP:
$conn = new PDO("dblib:host=azure-sql;dbname=my-database-name",
"username#m53man42a",
"my-secret-password");
My FreeTDS.conf:
[azure-sql]
host = m53man42a.database.windows.net
port = 1433
tds version = 8.0
client charset = UTF-8
text size = 20971520
Consider adding this as a bullet number 10 in your list... :D
Note that Microsoft have published a PHP7 extension for this, but if you're still on PHP5.x, that doesn't help you. I've succeeded in connecting using a different stack: freetds,odbc,pdo.
I'm using OS X 10.11.6 (El Capitan) with Macports, PHP5.6.
I've started by creating an Azure SQL Database called mydb on a server with a name of myserver.database.windows.net. It's important to remember to open the firewall to your client IP address, which you do on the server.
First step is to install freetds with the ODBC driver, and its PHP connector (change php56 to the correct version of your PHP):
sudo port install freetds +odbc
sudo port install php56-odbc
Next, you need to include some lines in your configuration files:
/opt/local/etc/odbcinst.ini
[FreeTDS]
Description = ODBC for FreeTDS
Driver = /opt/local/lib/libtdsodbc.so
Setup = /opt/local/lib/libtdsodbc.so
FileUsage = 1
This tells the odbc library where to find its odbc driver.
/opt/local/etc/freetds/freetds.conf
[myserver]
host = myserver.database.windows.net
port = 1433
tds version = 7.0
This tells the freetdc library where to find your server.
/opt/local/etc/odbc.ini
[myds]
Description = Test for SQL Server on Azure
Driver = FreeTDS
Trace = Yes
TraceFile = /var/log/sql.log
Database = mydb
Servername = myserver
UserName = myusername
Password = mypassword
Port = 1433
Protocol = 7.0
ReadOnly = No
RowVersioning = No
ShowSystemTables = No
ShowOidColumn = No
FakeOidIndex = No
This creates a data source called myds pointing at your database, enabling you to connect with the following PHP:
$conn = new PDO('odbc:myds', 'myusername', 'mypassword');
If any of this doesn't work for you, first check that the freetds installation is correct using:
tsql -S myserver -U myusername -P mypassword
And then check that the ODBC specifications are OK using:
isql -v myds myusername mypassword
Thanks to https://github.com/lionheart/django-pyodbc/wiki/Mac-setup-to-connect-to-a-MS-SQL-Server, which does the equivalent job for Python and which pointed me in the right direction for all this.

Categories