How to Connect to SQL through Windows Authenticated ODBC in PHP

For about the last year, I’ve been creating a CMS (content management system), for the automatic management and maintenance of my company’s eCommerce site, on the Yahoo! Store platform. The software imports the entire store automatically, runs a series of cleanup processes with about a dozen different criteria, saves the changes it has made, exports the modified pages, and makes them available to download from Jada’s interface. This automation cuts the need for about 3-4 people doing a weeks’ worth of work, and does it all automatically in 10-30 minutes. The one thing it doesn’t do, is the one cleanup process that takes the longest, and requires the most human thought: comparing every product’s available options on the site, and checking them against actual inventory in the order management software.

Until now.

Our current order management software runs as a MS Access front-end to a MSSQL 2005 server backend through and ODBC DSN connection. This connection has been limited to MS Access and MS Excel application/queries, and thus, was the limiting factor to writing this most-complex cleanup process into Jada. The most difficult part in my development was finding an understandable article describing how to make an ODBC call, and then actually get the data back, in the same simple manner that one makes a MySQL query. The real issue has been once the connection is closed, the result cannot be accessed. I had to find that out the hardway, via Microsoft’s convoluted documentation on using ODBC.

Here’s the code I’ve used to make the ODBC connection in PHP (unfortunately my blog’s template can’t handle actual code right now):

Code Breakdown

We’ll start creating a function that makes an ODBC connection, passes it an SQL query, then parses the data into a table/array and return the array.

Function call

function odbcQuery($sql, $attempt="") {

When we call the function, we’ll provide the SQL Query we want executed, and an optional description of what we’re trying to do with the query. In this way, if it errors, an semantic error will be displayed along with the technical one to help locate the code easily.

Database Connection

// Establish an odbc connection with the database
$link = odbc_connect("My_DSN_Name", "", "");

When running odbc_connect() it takes 3 parameters:

  • the DSN; Server,Port; or Server/SQLInstance
  • username
  • password

When connecting using Windows Authentication & a DSN (as this example is about), there are some caveats and things to remember:

  1. On the web server, the User running the Web Service process needs to be a User with permission to access the SQL Server.
    1. In my case, the user running the web server is SYSTEM, and so the user trying to access the SQL server is “DOMAIN\COMPUTERNAME$“.
    2. There is no password for a SYSTEM account, and so on the SQL Server needs to have a user created named “DOMAIN\COMPUTERNAME$“.
    3. Due to some security concerns, I’ve decided to give the account read-only access to the database I want to access. You’ll need to consult your own IT Administrator or security advisor for your security concerns.
  2. In the odbc_connect() statement, you then only need the name of the DSN (which I assume has already been configured on the Web Server you’re using) , followed by two null-quotes: “”.

This creates an active link via ODBC to the SQL Server…supposedly

Database Connection Checking & Error Handling

if (!$link) {
	die('Could not connect: '.odbc_error().': '.odbc_errormsg());
} else {

Next, we check the link . If it just flat-out doesn’t exist, then we kill the program, throw an error message that will read: “Could not connect: <;insert odbc error code>;: <;insert odbc error text>;”. Otherwise, we move on…

Sending the SQL Query & Checking Response

$data = odbc_exec($link, $sql);
if($data === false) {
	echo "ODBC Query: ".$sql."

"; die("ODBC Query failed: ".$attempt."
Error: ".odbc_error()); } else {

Now that we have a valid link to the database, we’ll send a request for data using the odbc_exec() function. This function sends the connection resource ($link) and the SQL Query we want run ($sql). It will return a “ODBC result identifier” or false.

Since a result identifier could, I assume, be the number 0 (zero) I want to ensure that $data is actually false and not just zero. That’s where the triple === comes in. When doing conditional statements, using == will convert the data being compared into a true/false value, where zero or nothing = false and anything else = true. When you use === you test for an actual boolean value, meaning anything including zero = true and false = false.

If the query failed, and resulted in a false result, we’ll display an error message: “ODBC Query: <;insert actual SQL Query>; // ODBC Query failed: <;insert query description>; // Error: <;insert ODBC error code>;”. Otherwise, we’ll move on…

Parsing the Query Results – Column Headers

// Initialization
$row = $fields = $records = $result = array(); 	

// Get the result's column names
$count = odbc_num_fields($data);
for($x=1;$x<=$count;$x++) {
	$fields[] = odbc_field_name($data, $x);
}

We start off by initializing all the variables we're going to use in the next bit of code, to make sure they're empty.

Then we'll run odbc_num_fields() over the $data to get the number of columns we need to iterate through. For columns, the counting starts at 1, so the for-loop starts at 1.

Iterate through each column name and add it to an array, called $fields:

Array (
	[0] => field_name_1
	[1] => field_name_2
	[2] => field_name_3
)

Parsing the Query Results - Records

// Get the result's data: array[record#][column#] = value
$count = odbc_num_rows($data);
for($x=0;$x<$count;$x++) {
	odbc_fetch_into($data, $row, $x);
	array_push($records,$row);
}

Then we run odbc_num_rows() over the $data to get the number of rows we need to iterate through. For rows, the counting starts at 0, so the for-loop starts at 0.

Iterate through each record row and insert it to a temporary array $row using odbc_fetch_into(). Then take $row and put it into an array of records, $records giving you something like this:

Array (
	[0] =>; Array (
		[0] =>; record_1_column_1
		[1] =>; record_1_column_2
		[2] =>; record_1_column_3
	)
	[1] =>; Array (
		[0] =>; record_2_column_1
 		[1] =>; record_2_column_2
 		[2] =>; record_2_column_3
  	)
	[2] =>; Array (
 		[0] =>; record_3_column_1
 		[1] =>; record_3_column_2
 		[2] =>; record_3_column_3
  	)
 )

Making the data useable

Now that we've got two tables/arrays of data - the field/column names, and each record's array of data - it's time to make it usable in a format that we can consistently expect to be returned. There are two ways to do this. We can create an array listind every record as an array with column_name keys and values

// Return data in the format: array[record_id][column_name] = value
foreach($records as $rid =>; $record) {
	foreach($fields as $key =>; $name) {
		$result[$rid][$name] = $record[$key];
	}
}

or we can list every column as an array of record id's as keys and values.

// Return the data in the format: array[column_name][record_id] = value
foreach($fields as $key =>; $name) {
	foreach($records as $record) {
		$result[$name][] = $record[$key];
	}
}

Personally I find the first option to be more consistent with my results when calling a 2-dimensional result from MySQL queries, so it is the one I have gone with in my example at the start of the post, and in this description.

The foreach() statements describe a compilation of a $result array in this manner:

  1. For each item in the $records array, store the record_id as $rid, and the record array as $record.
  2. Then for each item in the $fields array, store its cardinality as $key and it's value/name as $name.
  3. Then compile an array, iterating through each of the fields, storing this $record's associated cardinality $key's value into the $result array's storage for this record's id ($rid) under the appropriate field name.

It's a lot easier to grasp than it sounds. Basically, take array from the Query Results - Records section, and replace the # with the column name in each: [#] =>; record_y_column_x, but store it as a different array, called $results. The resulting array would look something like this:

Array (
	[0] =>; Array (
		[column1] =>; record_1_column_1_data
		[column2] =>; record_1_column_2_data
		[column3] =>; record_1_column_3_data
	)
	[1] =>; Array (
		[column1] =>; record_2_column_1_data
 		[column2] =>; record_2_column_2_data
 		[column3] =>; record_2_column_3_data
  	)
	[2] =>; Array (
 		[column1] =>; record_3_column_1_data
 		[column2] =>; record_3_column_2_data
 		[column3] =>; record_3_column_3_data
  	)
 )

Close the connection, Return the result

		odbc_close($link);
		return $result;
	}
}

Now that we've stored the data we need from the volatile $data variable returned from the SQL Query into $result, we can close the connection to $link using odbc_close(), and then return $result for the program to do with it what it will.

Conclusion

This is just an example code that explains one way of many to extract a variable 1-2 dimension array of data from your SQL Query, using a Windows-Authenticated ODBC DSN connection. There are many other methods to do this, as well as security fixes, data scrubbing, and other modifications that one would probably want to do.

This is the first function I've written in any language to access an SQL Server via ODBC. This is also a function that has worked in tests, but that I have not yet put into production. I encourage you to take this bit of explanation and massage it into something that fits your needs in the code that you're writing, and don't rely on what I've got here as a written-in-stone example of good production-level code. This sample will change many times before I actually implement it.

Happy Hacking!

Technorati Tags: , , , , , , , , , , , ,

[[Oracle]] and tsnlocal.net

I’ve spent the last two weeks working on getting [[Oracle]] into the role she was designed to play…but have found it to be a bit more involved than I realized.

Originally, I set up the server to be a web server with php and sql capabilities. Then I realized I needed to FTP files to the web server, so I installed FileZilla Server. Once that was done, I started working on the webpage for tsnlocal.net. I got it up, and then wanted to play around with some other type of server, and decided on a Jabber server for instant messaging. I installed Wildfire.

Wildfire is extremely easy to setup and install – so once I finished that, I looked for a Jabber client. My first choice was a VoIP client called Jabbin, but I couldn’t get it to connect to the server – probably because I don’t have a VoIP Protocol on the server to support it. So I went with what we use at work, Exodus. It’s a fairly functional Jabber client – with chat rooms, IM rosters, subscriptions, and file transfer…and a bunch of other stuff, including plugins.

Once the Jabber service was set up, and I figured out how to connect to it, I realized that telling people to use my dyndns domain name was not going to work. So I had to figure out how to get my Godaddy.com domain name to link directly to my IP address. But, come to find out, I have to have a Top Level Domain for an IP address, or my dyndns must be a nameserver registered with the NS Registry, in order to use it as a nameserver. I spent 2 days setting up BIND on Windows XP (because there was very little help on the internet for how to do it). Then I jacked around with the Total DNS control settings on godaddy, and got the webserver to work like it should – almost.

So now you can join the jabber server with yourname@jabber.tsnlocal.net. Now that I had that working, I noticed that there were email settings like pop.tsnlocal.net and smtp.tsnlocal.net that could be set up, so I decided to look into running my own email server. I got in #bloodshotgamer on irc.gamesurge.net and asked some of the tecky people I talk to in there what they’d recommend. Duck-Lap recommended qmail for linux, but mentined MailEnable for Windows. I was hoping for an IMAP service so I could run the webpage side of it, but that was not included with this. I might upgrade the service to something new later on, but for now, this was easy to install, and has easy administration, which is what I’m looking for since most of these other services aren’t critical to the function of the server. BIND was about the only thing that was hell to configure…everything else was easily figured out once I had the info and a general grasp of what it does and how it does it.

So now, [[Oracle]] does these things:
- Web Server (Apache, PHP, MySQL)
- FTP Server
- DNS Server
- Email Server
- Jabber Server
- TeamSpeak Voicechat Server
- Hamachi server
- Google Desktop distributed indexing server for the hamachi shares (the essence of tsnlocal)
- and a keep-alive for the dyndns service linking my IP to the dynamic domain

That’s a lot for a little box…but I’m not done yet – I need to put ssh on it so I can telnet into it. I’m sure there are other things that I will find to do with it as time goes on too.

Technorati Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Update: tsnX Database Movement

I’m backing up the tsnX.3 Beta’s Database (with the posts, forums, and accounts) and going to start moving the tsnV database into the tsnX site. The site is going to be down for a bit, while I do this, and iron out the kinks of auth-access, and conversions. If things don’t go properly after a bit, I’ll restore the tsnX.3 database, and continue working on converting tsnV to tsnX again. There are some things that I can’t test just by looking at the SQL Code, and that I have to implement for it to be tested.

So check the pizzy for updates if the forums aren’t working. If, in the meantime, the server goes down for some reason, and you can’t get to thepizzy or tsn, then go to http://tsnblog.blogspot.com to fing out why.

Technorati Tags: , , , , , , , , , , , , ,

Project: tsnXchat

After using a flooble chatterbox from www.flooble.com, and trying to (unsuccessfully) hack it to get rid of the ads at the bottom, I have resolved to putting my newly developed AJAX skills to the test, to create an open-source version, with no ads. I’ll explain how you can make one too in this entry.
Continue reading

Technorati Tags: , , , , , , , , , , , , , ,