mysql union之后的php fetch数组

时间:2012-09-13 14:40:24

标签: php mysql arrays union fetch

这个mysql语法有什么问题?我将它复制到phpmyadmin,它完美无缺。当我试图从php获取数组但它返回“bool(false)”错误。

(
    SELECT 
        id, 
        cim, 
        'news' as kat 
    FROM 
        mbsz_news 
    WHERE 
        cim LIKE '%anystring%' 
        OR lead LIKE '%anystring%' 
        OR content LIKE '%anystring%'
) 
UNION 
(
    SELECT 
        id, 
        p_name, 
        'plaza' as kat 
    FROM 
        mbsz_plazas 
    WHERE 
        p_name LIKE '%anystring%' 
        OR uzemelteto LIKE '%anystring%'
) 
UNION 
(
    SELECT 
        id, 
        cim, 
        'book' as kat 
    FROM 
        mbsz_konyvtar 
    WHERE 
        cim LIKE '%anystring%' 
        OR kszam LIKE '%anystring%' 
        OR kiado LIKE '%anystring%'
)

PHP代码:

$res = mysql_query($sql);
while($row = mysql_fetch_array($res))
{
    echo $row['type'];
}

$res给出错误bool(false) 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

你必须声明sql变量。 e.g。

$sql = (
    (SELECT 
        id, 
        cim, 
        'news' as kat 
    FROM 
        mbsz_news 
    WHERE 
        cim LIKE '%anystring%' 
        OR lead LIKE '%anystring%' 
        OR content LIKE '%anystring%'
) 
UNION 
(
    SELECT 
        id, 
        p_name, 
        'plaza' as kat 
    FROM 
        mbsz_plazas 
    WHERE 
        p_name LIKE '%anystring%' 
        OR uzemelteto LIKE '%anystring%'
) 
UNION 
(
    SELECT 
        id, 
        cim, 
        'book' as kat 
    FROM 
        mbsz_konyvtar 
    WHERE 
        cim LIKE '%anystring%' 
        OR kszam LIKE '%anystring%' 
        OR kiado LIKE '%anystring%'
)

调用变量时,php应该有效吗?

$res = mysql_query($sql);
while($row = mysql_fetch_array($res))
{
    echo $row['type'];
}