MSSQL Driver for PHP5.3

Before using PHP5.3, I never had to worry about MSSQL support. PHP included a dll file to use with MSSQL Server 2000 and up. This is no longer true if you decide to upgrade to PHP5.3.x. For months I looked for ways to connect to our MSSQL Server using PHP5.3.x. I finally found the driver and it works. It’s called SQLSRV and you can download it from http://sqlsrvphp.codeplex.com. It’s easy to install, just read the CHM file.

  • Run the exe to unpack it
  • Rename the folder to Microsoft SQL Server Driver for PHP (optional)
  • Move this to your %Program Files% directory (optional)
  • Inside that directory you will find several dll files. It supports both NTS (Non Thread Safe) and TS (Thread Safe). You also need to choose between VC6 or VC9 compiler. This will determine which file will be used.
  • Copy that file to %Installation Directory%\PHP\ext\ (assuming you are using the ext directory for your extensions.
  • Edit your php.ini. In the extensions section add the following extension=php_sqlsrv_53_ts_vc6.dll – or whatever file you copied to your ext directory.
  • Restart your web server and that should be it.

Here’s a quick sample code to get you started.

<?php

$servername = "SQLSERVER_NAME_OR_IP";
$uid = "db_username";
$pwd = "db_passwd";
$connectionInfo = array (
"UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"database_name"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);

if ($conn === false) {
echo "ERROR: DB Connection";
die(print_r(sqlsrv_errors(), true));

}
$stmt = sqlsrv_query($conn, "SELECT * FROM table");

if ($stmt) {
while ($row = sqlsrv_fetch_array($stmt)) {
echo $row[0].’<br />’;
}
}

?>

That should do it. I have only tested this on Windows 7 Professional (32bit), MSSQL 2005 (32bit) Standard on a remote Windows 2008 Server Standard R2, PHP5.3.3, Apache2.2.15, and driver version 1.1 (version 2 is now available) . Make sure your MSSQL server can accept remote connections if it is on a different server than your web server. The above instructions shouldn’t be  too different on other versions.

If you have a phpinfo() page, you will see the image below.

sqlsrv_phpini

Hope this helps you get started. Happy coding.

Windows 2008 and MSSQL Server 2005 not allowing remote connections

If you think you checked every setting in MSSQL Server that allows remote connections, you may have missed the Windows firewall setting. I have installed MSSQL 2005 many times on Windows 2000 Server, 2003, and 2008 and never ran into the remote connection problem. What’s happening is I’m unable to connection using the Management Studio on another machine into the server.

  • Checked the Configuration Tools/SQL Server Configuration Manager
  • Checked SQL Browser service is running
  • Pinged the IP address
  • Checked the Surface Area Configurations and made sure it allowed local and remote connections using TCP/IP only

It turns out that Windows firewall didn’t add MSSQL to the exceptions list. So here’s how you do it. Run firewall.cpl to bring up the Windows Firewall settings. On the left click on “Allow a program through Windows Firewall”. Make sure you are on the “Exceptions” tab and click on “Add program…”. If it’s not on the list, browse for the sqlservr.exe. You will find this in [INSTALL_DIR]\MSSQL.1\MSSQL\Binn\sqlservr.exe.

I never had this issue before. Not sure what caused it. Maybe Windows 2008 SP2. The versions I’m using are Windows Server 2008 RC2 and MSSQL Server 2005 Standard.

Debian5 Lenny and MySQL Server 5.1.x

I am running Debian5 Lenny which is running Virtualmin and Webmin. The default configurations install MySQL server 5.0.51. MySQL’s website has version 5.1.x. I wanted to update the version on my Debian box. Unfortunately, Debian considers MySQL 5.0.51 as the stable version, while version 5.1.49 is considered unstable. You can install it by updating your /etc/apt/sources.list file. Add the following lines and save.

deb http://ftp.de.debian.org/debian/ sid main
deb-src http://ftp.de.debian.org/debian/ sid main

After saving the file, update the apt-get.

apt-get update

You can continue to use apt-get and install the newer version of MySQL server or use the Webmin web gui. You can search for it under System/Software Packages, then search for “mysql-server”. You will see the newer version. Before you install it, make sure you have backed up your database, it will remove the old one.

It took some time to find the information. I had to browse different websites and piece together the information. It’s funny how something this common, is hard to find a solution to on one web page. I hope this helps Linux noobs like me out there. Do keep in mind that Debian considers this version of MySQL unstable.

Connect to MSSQL 2005 using PHP

Here’s a couple of quick tips to connecting to a MSSQL 2005 server using PHP on a Windows webserver. You will need to enable the php_mssql.dll in your php.ini file.

Here’s the code to connect to the server.

<?php

$conn = mssql_connect(‘my_server’, ‘db_username’, ‘db_password’);
if (!$conn) { die(‘ERROR: Unable to connect to the database.’); }
mssql_select_db(‘database_name’);

?>

Here is a helpful function I found that will help escape strings. I found this at http://stackoverflow.com/questions/574805/how-to-escape-strings-in-mssql-using-php.

<?php

function ms_escape_string($data) {
//if ( !isset($data) or empty($data) ) return ”;
if ( !isset($data) or empty($data) ) return “””;         // modified to handle empty $data
if ( is_numeric($data) ) return $data;

$non_displayables = array(
‘/%0[0-8bcef]/’, // url encoded 00-08, 11, 12, 14, 15
‘/%1[0-9a-f]/’, // url encoded 16-31
‘/[\x00-\x08]/’, // 00-08
‘/\x0b/’, // 11
‘/\x0c/’, // 12
‘/[\x0e-\x1f]/’ // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, ”, $data );
$data = str_replace(“‘”, “””, $data );
//return $data;
return “‘”.$data.”‘”;        // modified to handle empty $data
}

?>

Here is a sample query to the database.

<?php

$id = ms_escape_string($_GET['id']);    // escape variable
$sql = ‘SELECT id FROM table_name WHERE id=’.$id.”;
$rs = mssql_query($sql);

if (!$rs)
{
echo ‘ERROR: Unable to get records. ‘.mssql_get_last_message();    // equivalent to mysql_error()
}else{
while ($row = mssql_fetch_assoc($rs))
{
echo ‘The id = ‘.$row['id'].’<br />’;
}
}

?>

Another thing I learned from the article is the equivalent of “mysql_insert_id()”. It is “SELECT @@IDENTITY”. To handle dates and make them friendly to PHP use CONVERT(VARCHAR, [date], 20). This will display it as if you are using date(‘Y-m-d H:i:s) – 24 hour format. So an example would be…

SELECT CONVERT(VARCHAR, getdate(), 20) AS now

I tried to use PDO but was having a hard time getting it to work. I kept getting errors that had something to do with functions. I searched for solutions and tried them but none worked for me. Also, the rowCount() will always return less than or equal to 0.

I had trouble on both sides PHP and Microsoft. This seems to be the best solution that works for me. Hope it helps others.

Using PEAR Pager with PHP PDO

This post will be addressing 2 things.

  1. How to use PEAR’s Pager class with PHP PDO
  2. Addressing PDO bug #44639 (http://bugs.php.net/bug.php?id=44639)

Two queries will be used for this task. The first query, you will count the rows of the recordset. The second query is the same as the first but it will have the LIMIT – this is what will be used to display the data on each page.

Let’s say we have the following table.

CREATE TABLE IF NOT EXISTS`blog`
(
`blog_id` int(11) not null auto_increment,
`blog_text` varchar(4000) not null default ”,
PRIMARY KEY `pk_blog_id` (`blog_id`)
) ENGINE=INNODB;

Now we’ll query the database and get the row count using PDO.

<?php

require_once(‘file-with-pdo-db-connection.php’);

$sql = “SELECT * FROM `blog`”;
$stmt = $dbh->prepare($sql);

if ($stmt->execute())
{
// begin pager
require_once(‘Pager/Pager.php’);
$params = array
(
‘totalItems’ => $stmt->rowCount,
‘perPage’ => 10,
‘delta’ => 5,
‘mode’ => ‘Sliding’
);

$pager =& Pager::factory($params);

$links = $pager->getLinks();
echo $links['all'];

// offset setup
list($from, $to) = $pager->getOffsetByPageId();
$from = $from – 1;
$perPage = $params['perPage'];

// 2nd query based on 1st with LIMIT – this will be displaying data per page
$stmt2 = $db->prepare($sql.’ LIMIT :from, :perPage’);

// address bug 44639 – forces the variables to have the property of integer instead of string so no quotes will surround it
$stmt2->bindValue(‘:from’, $from, PDO::PARAM_INT);
$stmt2->bindValue(‘:perPage’, $perPage, PDO::PARAM_INT);
$stmt2->execute();

while ($row_blog = $stmt2->fetch())
{
echo ‘<div>’.$row_blog['blog_text'].’</div>’;
}

}

$dbh = null;

?>

If you don’t use the bindValue, you will get an error in your query. Your second query would look something like this… SELECT * FROM `blog` LIMIT ’0′, ’10′ and the error would occur right after LIMIT. You cannot have quotes surrounding the numbers. It took a few hours of Googling but found the solution.

If you want to read more about PEAR Pager, visit http://pear.php.net/package/Pager/docs.

Here’s a tutorial I found that helped me out a lot – http://www.codediesel.com/php/simple-pagination-in-php/.