来自mysql的concat两列,并在下拉列表中显示不同的值

时间:2016-02-17 02:59:47

标签: php mysql pdo

我有以下代码来组合两列数据并在下拉列表中显示不同的值:

<?php

    include_once "connect.php";
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
    $stmt = $conn->query("SELECT DISTINCT A, B FROM Contracts WHERE something='Ssomething' as amount"); 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
       echo "<option value='" .  $row['amount'] . " " . $row['amount'] . "</option>"; 
    }
    $conn->db=null;

?>

我收到错误:

  

致命错误:在xyz第5行中的非对象上调用成员函数fetch()。

感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分:1)

SELECT DISTINCT A, B FROM Contracts WHERE something='Ssomething' as amount

您需要在mysql中使用特定的concat函数。

SELECT 
CONCAT(A, B) as amount
FROM ( SELECT DISTINCT A, B FROM Contracts WHERE something='Ssomething') x

答案 1 :(得分:1)

  

致命错误:在xyz第5行中的非对象上调用成员函数fetch()。

     

通常意味着查询失败并返回FALSE到您的$stmt对象。

在这种情况下,查询语法不正确,如果您编写一些错误检查,它会告诉您错误实际是什么

<?php
include_once "connect.php";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 

$stmt = $conn->query("SELECT DISTINCT CONCAT(A,B) as amount FROM Contracts WHERE something='Ssomething'"); 
if ( $stmt === FALSE ) {
    print_r($conn->errorInfo());
    exit;
}

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
   echo "<option value='" .  $row['amount'] . " " . $row['amount'] . "</option>"; 
}
$conn->db=null;
?>

查询中的错误是由于使用了something='Ssomething' as amount,因为您无法在选择条件中使用别名。

所以试试

SELECT DISTINCT CONCAT(A,B) as amount FROM Contracts WHERE something='Ssomething'

作为您的查询。但是,不同之处将变得不必要/不相关。