Rowcount() to get number of rows affected by Query
WE can use rowCount() to know number of rows or records affected by the latest sql statement involving any Delete , update , insert command. This function is to be used immediately after the sql execute command. This function works similar to mysql_affected_rows function
rowcount() to get number of records affected by Query involving any Delete , update & insert command
WE will learn some examples on how to use this in our pdo example table. Download the dump file of pdo_admin table at the end of the tutorial.
$count=$dbo->prepare("update pdo_admin set status='T' ");
//$count=$dbo->prepare("delete from pdo_admin where status='F'");
$count->execute();
$no=$count->rowCount();
echo " No of records = ".$no;
Output will show number of records updated or deleted from the table ( based on which line is executed )
No of records = 7
Same way let us try with one delete command
$count=$dbo->prepare("delete from pdo_admin where status='F'");
$count->execute();
$no=$count->rowCount();
echo " No of records = ".$no;
The output will show us number of records deleted from the pdo_admin table.
Same way you can do for insert command.
rowcount with SELECT Command
Usually rowCount() works with delete, update and insert commands but rowCount does not give reliable data when used with SELECT query in MySQL, so it is better to use Count command to get total number of records. Here is an example.
$nume = $dbo->query("select count(id) from pdo_admin")->fetchColumn();
echo "<br>Number of records : ". $nume;
Here id field we used as this is an auto incremented field. If such field is not there then we can use all the records like this.
$nume = $dbo->query("select count(*) from pdo_admin")->fetchColumn();