0

I have the following code that I am using to check for constraints on a database(for a class). U am trying to get the number of rows returned by the query and I keep getting the same error on the line

$count1= $ires1->numRows(MDB2_FETCHMODE_ASSOC);

Error:

> Call to a member function numRows() on a non-object

I've been pulling my hair out because my other functions similar to this one work fine, this is the only function that doesn't work. Is there something that stands out in this one?

The argument $db is just the connection to my database, pno is an integer and the essn is text.. So I'm not sure what I am doing wrong..

<?php
function submitCheck($db){
    $essn= $_POST['essn'];
    $pno=$_POST['pno'];

    $query1 = "select * from works_on where pno=? and essn=?";
    $types1 = array('integer','text');
    $stmt1 = $db->prepare($query1, $types1, MDB2_PREPARE_MANIP);

    if (MDB2::isError($stmt1)) {
        print("bad prepared statement:" . $stmt->getMessage());
    }

    $queryargs1 = array($pno, $essn);
    $ires1 = $stmt1->execute($queryargs1);
    $count1= $ires1->numRows(MDB2_FETCHMODE_ASSOC);
    //print("The project number entered was $count1[pno]");
    if(!(count($count1)==0)){
        print("The employee is already part of this project! If you want to update the hours, please select update!");
        return false;
    }
    return true;
}
?>
Oerd
  • 2,256
  • 1
  • 21
  • 35
Paul
  • 21
  • 1
  • 1
    What is the value of `$ires1`? Is it possible the query fails and `$stmt1->execute` returns some error value instead? (like `false`, or `null`) – Halcyon Apr 28 '11 at 20:07
  • I think it does return a null value, which is why it wasn't working. – Paul Apr 28 '11 at 20:32

1 Answers1

2
$count1 = $stmt1->rowCount();

$ires1 is not an Object, but a boolean, as stated in PHP PDOStatement::rowcount documentation.

A warning though, from the PHP.net site:

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

There you have their suggested solution too:

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action."

I did not know and I couldn't find information on method numRows, so that's as far as I can go. Good luck!

Oerd
  • 2,256
  • 1
  • 21
  • 35
dbind
  • 21
  • 1
  • 1
    @Paul, if it helped then you should at least add an _upvote_ to this answer and if it ultimately answered your question then mark this answer as the accepted answer – Oerd Apr 28 '11 at 21:28