in reply to building sql statement

With complicated if-then logic like this, indentation can be a great way of detecting structural problems. Edit your post to use code tags, please, so we can see any indentation in your source. That will also help with the $x versus [$x] problems too.

References to single array elements should have the $ sigil instead of @:

$dbcolumn[$x] instead of @dbcolumn[$x]

Your loop contains that variable $x but it really isn't necessary. Using the foreach loop with an array is one way of avoiding array indexes. The following are equivalent:

for ($x = 0; $x <= $#array; $x++) { ... $array[$x] ... } versus foreach $element (@array) { ... $element ... }
But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)