Search and display of results 2 tables mysqli/php

Asked

Viewed 298 times

1

I wanted to do a search in 2 tables (news and photos) and then display the results of this query below. But the fields I have in each table are different and I’m not able to elaborate a way to display the results because of this.

Fields from the news table: Title, photo, description, content, date

Fields of table photos: Title, photo, date, location

Ex:

  1. Search the term "test"...
  2. Query in the two tables and brings all the results found.

The search result wanted to look like the image: inserir a descrição da imagem aqui

Note: The layout of the image is just an example, what I am not able to do is the code that generates the result. If it was the result of a table only displaying results only of it I can do, but displaying results of 2 tables together and merged I could not.

  • What you have code so far?

  • Actually nothing. But I will post as use to display results of a table.

  • From a read in https://answall.com/questions/208941/como-fazer-inner-join-em-mysql

1 answer

2


You need to match the fields of the two tables, so the amount and name of the returned columns will be equal.

SELECT `titulo`, `foto`, `descricao`, `conteudo`, `data`, '' as `local`
FROM `noticia` WHERE [sua pesquisa]
UNION
SELECT `titulo`, `foto`, '' as `descricao`, '' as `conteudo`, `data`, `local`
FROM `fotos` WHERE [sua pesquisa];

And when displaying you validate if the field is not empty to be displayed.

if (isset($query['campo']) && !empty($query['campo'])) {
     echo $query['campo'];
}
  • 2

    I gave +1 in the answer because it is correct, but only one observation: the names do not need to be equal in UNION, you can select by position of the fields as well, both in SQL and PHP. (using numbers instead of names in SQL, and in PHP picking the numerical array instead of associative)

  • 1

    Very good, it worked correctly to what I needed. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.