4

I've encountered a little problem. I have the following code:

    $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);

Which returns:

array(0) { } 

I've tried the query in phpmyadmin and it worked fine. Can you please help me find the error?

Matt Busche
  • 14,216
  • 5
  • 36
  • 61
Chris Illusion
  • 277
  • 2
  • 5
  • 18

1 Answers1

4

Accorrding to the documentation

You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

In you case, you should use something like

$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'] 
                         )
                   );  
Luc M
  • 16,630
  • 26
  • 74
  • 89