PDO提取不返回任何内容

时间:2013-03-04 00:08:14

标签: php mysql pdo

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

    $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中尝试了查询,但它运行正常。能帮我找到错误吗?

1 个答案:

答案 0 :(得分:3)

Accorrding to the documentation

  

您不能在a中两次使用同名的命名参数标记   准备好的声明   您无法将多个值绑定到for中的单个命名参数   例如,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'] 
                         )
                   );