What is causes this error? How can fix it?
$find = 'hello';
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE "%' . $find . '%" UNION SELECT * FROM tour_foreign WHERE name LIKE "%' . $find . '%"');
Error:
A Database Error Occurred
Error Number: 1222
The used SELECT
statements have a different number of columns
SELECT * FROM
tour_foreign_residence WHERE name LIKE "%hello%" UNION SELECT * FROM
tour_foreign WHERE name LIKE "%hello%"
Filename:
D:\xampp\htdocs\system\database\DB_driver.php
Line Number: 330
There two main rules for using UNION
operator:
- Count and ordering retreived columns should be equal in union queries
- Type of data in appropriates columns must be compatible
In your case, first rule is ignored.
use join
operator instead
Are you sure you need an UNION?
UNION requires that all the queries that you're uniting have the same number of columns in the SELECT clause, so you shouldn't use the *, but esplicitly write the fields you need to query. Also, the clumns need to have the same data type.
Dont use SELECT *
in your query. Instead write down the actual column names that you want the get from the database. The column names should be same from both the tables. You currently have a UNION
and it looks like that tables tour_foreign_residence
and tour_foreign
has different columns.
According to w3schools article about UNION operator:
Each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types.
Also, the columns in each SELECT statement must be in the same order.