简体   繁体   中英

Use UNION in Codeigniter and get error?

I want select data with UNION as follow:

$find = 'hello';
$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE '%$find%' UNION SELECT * FROM tour_foreign WHERE name LIKE '%$find%''); // Line number 46

But I encounter this error:

> A PHP Error was encountered<br> Severity: Warning<br> Message:
> Division by zero<br> Filename: foreign.php<br> Line Number: 46<br>
> 
> A Database Error Occurred<br> The query you submitted is not
> valid.<br> Filename:
> D:\xampp\htdocs\system\database\DB_driver.php<br> Line
> Number: 257<br>

How can I fix it?

Update:

Error:

> A Database Error Occurred<br> Error Number: 1222<br> The used SELECT
> statements have a different number of columns<br> SELECT * FROM
> tour_foreign_residence WHERE name LIKE "%hello%" UNION SELECT * FROM
> tour_foreign WHERE name LIKE "%hello%"<br> Filename:
> D:\xampp\htdocs\system\database\DB_driver.php<br> Line Number: 330<br>

You're throwing single quotes in the string without escaping them. That could be your problem.

Table tour_foreign_residence and tour_foreign have a different number of columns. Remove * after each select to set the same number of columns.

Change this:

$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE '%$find%' UNION SELECT * FROM tour_foreign WHERE name LIKE '%$find%'');

to

$data = $this->db->query('SELECT * FROM tour_foreign_residence WHERE name LIKE "%' . $find . '%" UNION SELECT * FROM tour_foreign WHERE name LIKE "%' . $find . '%"');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM