Reputation: 147
I'm trying to search all tables and columns for a certain value and I'm using php connection to IBM DB2 database. I was wondering if the error is cause because of multiple usage of union.
This is my error message :
Improper use of a string column, host variable, constant, or function "NAMABARANG". SQLSTATE=42907 SQLCODE=-134
And here is my code :
$keyword=$_GET['keyword'];
$query="SELECT * FROM INVENTORY WHERE NAMABARANG LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE ARRIVALDATE LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE PAPERNUMBER LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE SERIALNUMBER LIKE '%".$keyword."%'".
" UNION SELECT * FROM INVENTORY WHERE CONDITION LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE LOCATION LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE CONFIRMATIONDATE LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM INVENTORY WHERE BARCODE LIKE '%".$keyword."%'".
" UNION ALL SELECT * FROM USERANDPASSWORD WHERE USERNAME LIKE '%".$keyword."%'";
" UNION ALL SELECT * FROM USERANDPASSWORD WHERE ACCESS LIKE '%".$keyword."%'";
Upvotes: 3
Views: 10408
Reputation:
See info on that error message here. The problem appears to be that NAMABARANG
is one of the long character/clob types, and it is illegal to have that in a query that performs grouping. This query performs grouping because one of the sub-queries uses UNION
rather than UNION ALL
. UNION
groups when it removes duplicate rows.
A query like this should probably not return all columns (SELECT *
). Instead, only return what you really need. Possibly an ID column that can identify each row that matched, and the name of the column and table that matched. This will remove the error.
A few other points:
USERANDPASSWORD
have the exact same columns as INVENTORY
? If not, this union will not work. Solves this by not selecting *
, instead select a similar set of columns from each table.UNION ALL
. Otherwise, use UNION
to remove duplicates.Upvotes: 3