Jump to content


Photo

Concatenation of variables from an array to forma a sql query


  • Please log in to reply
3 replies to this topic

#1 pravonline

pravonline
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 24 May 2006 - 07:15 AM

Dear All,

I would like to how to concatenate the values from an array to form a complete sql query, say for example

The array looks like this :

Arraytest[1] = "SELECT"
Arraytest[2] = "*"
Arraytest[3] = "FROM"
Arraytest[4] = "TABLE1"
Arraytest[5] = "WHERE"
Arraytest[6] = "NAME"
Arraytest[7] = "="
Arraytest[8] = "BUSH"

And from this i need to form a SQL qury like this ""SELECT * FROM TABLE1 WHERE NAME = 'BUSH'" and need to pass this into a Variable "$test", number of subscript of this array depends upon the length of query, can any one guide me how to do this? Since i'm a mainframe professional and new to this technology!!

Thank you,
Antony


#2 hvle

hvle
  • Members
  • PipPipPip
  • Advanced Member
  • 667 posts
  • Locationmelbourne, Australia

Posted 24 May 2006 - 07:41 AM

This script below only work with SELECT, meaning it won't work if the query is update, insert ....

you can do a little hack first, it is to insert a \' around values (like BUSH) in this example.

    for ($i = 0; $i < count($Arraytest); $i ++) 
   {
       if ($Arraytest[$i] == '=')
       {
            $Arraytest[$i+1] = "'". $Arraytest[$i+1] . "'";
            $i ++;
       }
    }

Above block will find any occurent of = and wrap the single quote around the next one.


    $sql = implode(' ', $Arraytest);
above code simply concat the array by space.

I understand you want a code that worked with all query. However it is depend on what kind of query to concatenate the sql.


Life's too short for arguing.

#3 Honoré

Honoré
  • Members
  • PipPipPip
  • Advanced Member
  • 66 posts
  • LocationAntwerp - Belgium

Posted 24 May 2006 - 07:43 AM

Probably impossible to do without additional information.
You need to know which array elements are SQL reserved words, table or column names, data values.
Non numeric values should appear between quotes, database - table - column names should be between back quotes, ...

#4 pravonline

pravonline
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 24 May 2006 - 03:50 PM

Dear Mr.hvle,

[img src=\"style_emoticons/[#EMO_DIR#]/smile.gif\" style=\"vertical-align:middle\" emoid=\":smile:\" border=\"0\" alt=\"smile.gif\" /] Thanks for your valuable code and suggestion, I acheived the required result with your sample code, Thank you so much once again Mr. Hlve.

Dear Mr.Honoré,
Thanks for your valuable suggestion

Regards,
Antony




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users