pdo fetch count code example
Example 1: pdo fetch
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");
print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");
print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");
print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->name;
print("\n");
?>
Example 2: sql row count php pdo
<?php
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
Example 3: number of rows in a mysql table pdo
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=my_database',
'username',
'password'
);
$sql = "SELECT COUNT(*) AS num FROM users";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['num'] . ' users exist.';