Accessing XML column of SQL Server from PHP (PDO)

One cool feature that SQL Server provides is the XML data type. This enables to save XML data as it is just like any other data type in the database.

Once we put the xml, then we can apply XPath to query the data from the sql server nifty IDE.

But, when you try to use the same query outside of the IDE, you would not be able to get the data as expected.

I was working on PHP project where the data (XML) has to be retrieved from SQL Server. Here is the hack step by step

1. Configure your PDO
Say:


try {
    $hostname = "host";            //host
    $dbname = "dbname";            //db name
    $username = "user";            // username like 'sa'
    $pw = "pass";                // password for the user

    $dbh = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "n";
    exit;
  } 
**taken from php.net

2. Once you got the handle ($dbh) add the following on the handle:


$handle = getHandle(); //function like above to give you the handle
$handle->exec('SET QUOTED_IDENTIFIER ON');
$handle->exec('SET ANSI_WARNINGS ON');
$handle->exec('SET ANSI_PADDING ON');
$handle->exec('SET ANSI_NULLS ON');
$handle->exec('SET CONCAT_NULL_YIELDS_NULL ON');

That is all, this are actually additional parameters that sql server would add when sending xml based query to the engine.

Happy XMLing :)

Adding PECL package in Ubuntu

I remember once enjoying PECL (PHP Extension Community Library)on my machine flourishingly. All of the sudden, I was not able find it – here is how I find out.
Trying to play with the new MongoDb, I had to install the driver from the the repository as

sudo pecl install mongo

This time I got the wrong message of not having the pecl. It was easy though – just

sudo apt-get install php5-dev

As the PECL can be found inside it.
I have read some blogs complaining this one not working and passing the problem through installing the PEAR pachage – WHICH EVER IS EASIER.
Happy PECLing..

Getting list of sub and super class member variables

On my project, I need to collect the member variables of the classes that I am working on.
But, since, the classes have common member variables like date_created and date_modified and others, I have Abstract class for those member variables and their setters and getters
I have been using get_class_vars for such cases, but I want to call this from the parent and be able to access the member variables at run time. which was a problem, it would collect only the parent member variables:

        $classProperties = array();
        $classProperties['vars'] = get_class_vars(get_class($this));

But this hasn’t work.
Then I used the reflection method:

        $child_reflection = new ReflectionClass($this);
        $child_properties = $child_reflection->getdefaultProperties();
        $parent_reflection = new ReflectionClass(__CLASS__);
        $parent_properties = $parent_reflection->getdefaultProperties();
        $class_properties['vars'] = array_merge($child_properties
, $parent_properties);

This would give all properties for the class. In this case it should be up to the developer to limit the access and manipulate the use of the properties not to loose the semantics of having them :-)

d i s   i z – IT!

Number formatting in PHP

OK while coding numbers are almost always there. Bit it stat, some calculation, rate finding … a lot is on numbers.
Saying so, we might want to beautify our numbers on displaying or storing or making them an input for another usage or we just want it.
PHP has the function number_format() for this usage: this accepts up to 4 parameters where we can supply either one, two or four of them.

lets have this number 456234.3451678 as a result of some calculation.
$number = 456234.3451678;
Taking the integral part:
we can do this in different methods
1. casting it to integer:

(int)$number;

2. using built-in function:

number_format($number); // output -> 456,234

3. using regex:

 
        $pattern="/.d*/";
        $number = preg_replace($pattern, '', $number);

After this operation, we might need to cast it back to the number for type safety cases.
Also we can use str_replace

Limiting number of decimals after decimal point
This also can be achieved in different ways:
1. Using function:

number_format($number, 2); //takes the two digits next to decimal point

2. Using regex:

preg_match('/(d+(.?d{0,2})?)/', $number, $matches); // here matches[0] would contain the required value

SimpleXMLElement not working with some XML

What other object would make life easier in regard to XML manipulation in PHP other than SimplXMLElement.
I was using this object in deciphering the SOAP response, I could have used other tools for SOAP actually, and found out the object is not happy when it guests xmlns.
All I have to do was to replace the xmlns whole part and SimpleXMLElement was happy :)

Unknown modifier ” error preg_match

Running this error while adopting preg_mathc in php? Just check if the delimiters are not used in your string – mostly this would fix the problem.

$example = "<root><tag1>content1</tag1></root>";
$pattern = "/<tag1>.+</tag1>/";
preg_match($pattern, $example, $matches) ; 

If you run the above snippet, you would run the error as the delimiter ‘/’ is the part of the string – so changing the delimiter, say, to ‘?’ would solve the problem. like

 $pattern = "?<tag1>.+</tag1>?

Hope it would help.

Changing default Apache webroot in Ubuntu

By default the webroot for apache/php is in /var/www

To change this, say, to /home/user/workspace/public_html

1 Go to file: /etc/apache2/sites-available/default
2. Change the /var/www to /home/user/workspace/public_html – as simple as this!!

OR,

If you are changing root just to abscond some difficulty from your IDE or just for temporary purpose, you can use the symlik: just open your terminal and –
cd /home/user/workspace/public_html
ln -s /var/www/project project

PHP is displaying questionmark (???) for unicode

One of the fun things in php-mysql is working with Unicode characters. It is so cooked that, we should almost eat those with a little bit adjustment.
I am not going to tutor on how to use php-mysql unicode stuff – there are a bunch of ’em out there.
Rather I would discuss an error that would be common while doing your stuff..
Once you configure everything and put your unicode to mysql, you might see the output of it being questionmark on the browser – but you see the correct unicode in the database through the phpmyadmin.. it is this single line of code you would ever need…
mysql_query(“SET NAMES ‘utf8′”, conn); where the conn is the result of your connection – mysql_connect();
You can modify it accordingly, for example I am using an object oriented one so I can issue the query from my object – you would need to do this only once.

Happy unicoding..

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

A connection attempt failed error

It looks on windows php5.3 has some kind of confusion on localhost :)

I have been using the earlier version without any problem and the moment I update to the newer version.

I got error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

As a remedy, just change the localhost with 127.0.0.1 and it will work like a charm…

Prev –

mysql_connect('localhost', 'root', 'root'); 

To

mysql_connect('127.0.0.1', 'root', 'root'); 

Click here to See how you can upgrade mysql

While you are here, I would recommend for you:

Do you know how to add scroll bar to mysql terminal?

How I setup LAMP on AWS step by step

Learn nodeJs with AngularJS in a complete project step by step

Fatal error: Using $this when not in object context in PHP

Whenever you got this error check the following:

1. Make sure the $this-> is used inside the object and referring to the class’s and inherited non-static members.

2. Make sure the called members of the object are properly addressed as static or member/function variables

Do you know the different different post types?

Here is an example for the second one.

Assume you have the following object


class Example
{
   function getExampleText()
   {
      return "Example Text";
   }
   static function getStaticExampleText()
   {
      return "Static Example Text";
   }
}

While accessing, if the code tries something like this one,

$example = new Example();
Example::getExampleText(); //Trying to access non-static as static

Then you would have the error