Search in php with UNION - mysql_num_rows error

0

I am making a simple search system that only brings the result amounts of the specified tables. The problem is that it is causing an error because the tables are different and their lines are different. See my script.

$q = $_GET['busca'];

$query= '
        SELECT * FROM noticia WHERE noticia_title LIKE "%'.$q.'% or noticia_content LIKE "%'.$q.'%"
    UNION
        SELECT * FROM eventos WHERE evento_nome LIKE "%'.$q.'% or evento_content LIKE "%'.$q.'%"
        UNION 
    SELECT * FROM albuns WHERE album_name LIKE "%'.$q.'%" or album_descricao LIKE "%'.$q.'%"  
    ';

    $result = mysql_query($query);
    $count = mysql_num_rows($result);

    if ($count == 0) {
        echo "Nenhum resultado!";
} else {
    if ($count == 1) {
        echo "1 resultado encontrado!";
}
        if ($count > 1) {
        echo "$count resultados encontrados!";
    }
        while ($dados = mysql_fetch_array($query)) {
        echo "";
    }
    }              

The error that is being caused is: Warning: mysql_num_rows (): supplied argument is not valid MySQL result resource in

Can anyone help me?

    
asked by anonymous 27.03.2018 / 15:41

1 answer

3

As discussed in the comments:

1) Double quotes were missing in the first two selects

SELECT * FROM noticia WHERE noticia_title LIKE "%'.$q.'%" 
SELECT * FROM eventos WHERE evento_nome LIKE "%'.$q.'%"

2) After adding mysql_query($query) or die(mysql_error()); the following error was identified:

  

The used SELECT statements have a different number of columns

3) To solve this problem you should make a SELECT with the same amount of columns. Example:

$query= '
        SELECT noticia_id FROM noticia WHERE noticia_title LIKE "%'.$q.'%" or noticia_content LIKE "%'.$q.'%"
    UNION
        SELECT evento_id FROM eventos WHERE evento_nome LIKE "%'.$q.'%" or evento_content LIKE "%'.$q.'%"
    UNION 
        SELECT album_id FROM albuns WHERE album_name LIKE "%'.$q.'%" or album_descricao LIKE "%'.$q.'%"  
    ';
    
27.03.2018 / 16:41