4

我遇到了一个小问题。我有以下代码:

    $query = $db->prepare('(SELECT last_visit, last_ip FROM user_log WHERE user_id = :id) 
                            UNION
                           (SELECT time AS last_visit, packet_hex AS last_ip FROM crack_log WHERE target_id = :id)
                            ORDER BY last_visit DESC LIMIT 0,10;');
    $query->execute(array(':id'=> $_SESSION['id']));
    $log = $query->fetchAll(PDO::FETCH_ASSOC); //Last visit/IP

    var_dump($log);

返回:

array(0) { } 

我已经在 phpmyadmin 中尝试过查询,它运行良好。你能帮我找出错误吗?

4

1 回答 1

4

根据文档

您不能在准备好的语句中两次使用同名的命名参数标记。您不能将多个值绑定到单个命名参数,例如 SQL 语句的 IN() 子句。

在你的情况下,你应该使用类似的东西

$query = $db->prepare('(SELECT last_visit, 
                               last_ip 
                        FROM user_log 
                        WHERE user_id = :id_1
                       ) 
                        UNION
                       (SELECT time AS last_visit,
                               packet_hex AS last_ip 
                        FROM crack_log 
                        WHERE target_id = :id_2
                       )
                       ORDER BY last_visit DESC LIMIT 0,10;'
                     );
    $query->execute(array(':id_1'=> $_SESSION['id'],
                          ':id_2'=> $_SESSION['id'] 
                         )
                   );  
于 2013-03-04T00:16:10.530 回答