1

I have the following code to combine the two columns data and display distinct values in the dropdown list:

<?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;

?>

I get the error:

Fatal error: Call to a member function fetch() on a non-object in xyz line 5.

Any help is appreciated. Thank you in advance.

miababy
  • 225
  • 2
  • 16
  • `var_dump($stmt);` before the `while` You will see something interesting. –  Feb 17 '16 at 03:12

2 Answers2

2

Fatal error: Call to a member function fetch() on a non-object in xyz line 5.

Normally means the query has failed and returned FALSE into your $stmt object.

In this case the query syntax is incorrect, if you code some error checking it will tell you what the error actually is

<?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;
?>

The error in the query is due to the use of something='Ssomething' as amount because you cannot use an alias in a selection criteria.

So try

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

as your query. But the distinct would then become unnecessary/irrelevant.

Community
  • 1
  • 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1
SELECT DISTINCT A, B FROM Contracts WHERE something='Ssomething' as amount

You will need to use a specific concat function in mysql.

SELECT 
CONCAT(A, B) as amount
FROM ( SELECT DISTINCT A, B FROM Contracts WHERE something='Ssomething') x
Ed Baker
  • 643
  • 1
  • 6
  • 16