askseekknock askseekknock - 2 months ago 7
MySQL Question

Combine mysql query result

I am searching for words that contain "un" from two columns in a database table.
How can I get both row data in the output $data?

Example:

col1 | col2


tom -------- unfriendly

train ------- fast

unused--- cloth


.

$query = mysql_query("SELECT * FROM table
WHERE col1 LIKE '%un%'
OR col2 LIKE '%un%'
ORDER BY col1 ASC");
while ($row = mysql_fetch_array($query)) {
$data[] = $row['col1'];
}


I get $data = [tom,unused] from the above code.
How can I get $data = [ tom - friendly, unused - cloth] ?

Answer

Try using CONCAT:

SELECT CONCAT(col1, ' - ', col2) AS result
FROM table 
WHERE col1 LIKE '%un%' OR
      col2 LIKE '%un%' 
ORDER BY col1 ASC

And then you would access the result set in your PHP code via:

while ($row = mysql_fetch_array($query)) {
    $data[] = $row['result'];
}
Comments