0

Trying to return the total row count for a sql table. My code returns the number of rows that are added not the total number of rows in the table. Any suggestions?

PHP:

require(ROOT_PATH . "inc/database.php");
try {
    $query = $db->prepare("REPLACE INTO launch_email VALUES ('$email')");
    $query->execute();
    $count = $query->rowCount();
    echo $count;
} catch (Exception $e) {
    echo "Data could not be submitted to the database.";
exit;
1
  • I am using MAMP with PHP 5.2.17 Commented Apr 14, 2014 at 4:22

2 Answers 2

1

rowCount() ist not a direct method of the PDO class, it is a method from PDOStatement.

Syntax:

public int PDOStatement::rowCount ( void )

Example based on your approach:

try {
    $query = $db->prepare("REPLACE INTO launch_email VALUES ('$email')");
    $query->execute();
    $count = $query->rowCount();
} catch (Exception $e) {
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

So your code works. However, its not what I was looking for exactly. I have edited my post to reflect the changes. But what I was intending to do was to return the total number of rows in the table, not just the number of rows that I changed. My PDO object that I create in my database.php file is $db. Would it be easier to do a sql count function instead?
I now understand that I have been attempting my intended solution with the wrong method.
@RyanSalmons Exactly. If you want to determine that, you have to SELECT it after you have updated your records, for example with a COUNT in it. Your UPDATE/REPLACE-statements will only return you the affected rows. It might look like this: SELECT COUNT(*) FROM launch_email WHERE yourfield = "somevalue";
0

PDO::exec returns the number of affected rows.

So you don't need to use rwoCount(), and note rowCount() is the method from PDOStatement.

require(ROOT_PATH . "inc/database.php");
try {
    $count = $db->exec("REPLACE INTO launch_email VALUES ('$email')");
} catch (Exception $e) {
    echo "Data could not be submitted to the database.";
    exit;
}

Comments

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.