1

I'm trying to get the results from a Select statement using fetchALL() but nothing is working for some reason. Here is a sample of the code:

$vars = array(':name' => $_POST['name'], ':id' => $_POST['id']);

$stmt = $dbh->prepare("SELECT * FROM temp_table WHERE name=:name AND id=:id");

if($stmt->execute($vars)){
    if($stmt->fetchColumn() > 0){
        echo "Found";
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        print_r($result);
    }else{
        echo "Not found";
    }
}else{
    echo "Error";
}

The statement executes successfully, and it finds one column, like it should, and it echos "Found", but the array comes up as empty, it just comes up as array() Everything executes well, it's just that fetch, or fetchAll() always returns empty. Any help would be appreciated!

3
  • What do you see if you run that SQL statement in the MySQL monitor? How many rows? Commented Dec 22, 2014 at 2:02
  • 2
    Assuming your query is returning just one row, fetch_column() is fetching it to extract the column data. When you then call fetchAll() the data has already been fetched and there's no more. Commented Dec 22, 2014 at 2:03
  • ^ You're totally right, I got it now lol, thanks guys Commented Dec 22, 2014 at 2:08

1 Answer 1

4

You are trying to fetchAll after fetchColumn.

fetchColumn

Returns a single column from the next row of a result set or FALSE if there are no more rows.

fetchAll

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set.

So, you could rewrite it like this.

 if($result = $stmt->fetchAll(PDO::FETCH_ASSOC)){
        echo "Found";
        print_r($result);
 }else{
        echo "Not found";
 }
Sign up to request clarification or add additional context in comments.

1 Comment

This was it, I literally figured it out right after I posted the question too lol, but thanks for the help! And +1 for the right answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.