PHP从两个表和echo表名中选择

时间:2014-01-29 16:36:40

标签: php mysql sql pdo

我正在使用这个PHP代码从MySQL中使用UNION

从2个表中进行选择
$sql="
    SELECT 
    'ticket_updates' as rowTable,
    sequence, 
    ticket_seq, 
    notes as displaydata, 
    datetime as timestamp, 
    updatedby, 
    CONCAT('<strong>Time Start: </strong>',timestart,' - <strong>Time End: </strong>',timeend) as timestartend
    from ticket_updates where ticket_seq = '".$_GET["seq"]."'

    UNION

    SELECT 
    'ticket_changes' as rowTable,
    sequence, 
    ticket_seq, 
    description as displaydata, 
    datetime as timestamp,  
    changed_by as updatedby, 
    blankfield
    from ticket_changes where ticket_seq = '".$_GET["seq"]."' 

    ORDER by timestamp ASC ";

$stmt = $pdo_conn->prepare($sql);
$stmt->execute(array(':ticket_seq' => $_GET["seq"]));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$num_rows = count($records);
foreach ($records as $result2) {
   echo $result2["rowTable"];
}

但它没有回显ticket_updatesticket_changes

我知道有行返回,因为当我在phpMyAdmin中运行查询时,它显示行并显示ticket_updatesticket_changes

1 个答案:

答案 0 :(得分:1)

您的SQL中没有任何占位符与execute调用中的参数匹配。试试这个:

$sql="
    SELECT 
    'ticket_updates' as rowTable,
    sequence, 
    ticket_seq, 
    notes as displaydata, 
    datetime as timestamp, 
    updatedby, 
    CONCAT('<strong>Time Start: </strong>',timestart,' - <strong>Time End: </strong>',timeend) as timestartend
    from ticket_updates where ticket_seq = :ticket_seq1

    UNION

    SELECT 
    'ticket_changes' as rowTable,
    sequence, 
    ticket_seq, 
    description as displaydata, 
    datetime as timestamp,  
    changed_by as updatedby, 
    blankfield
    from ticket_changes where ticket_seq = :ticket_seq2 

    ORDER by timestamp ASC ";

$stmt = $pdo_conn->prepare($sql);
$stmt->execute(array(':ticket_seq1' => $_GET["seq"], ':ticket_seq12' => $_GET["seq"]));

您需要两个不同的占位符,不能两次使用相同的占位符。