pdo fetch count code example

Example 1: pdo fetch

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
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
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
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

//Instantiate the PDO object and connect to MySQL.
$pdo = new PDO(
    'mysql:host=127.0.0.1;dbname=my_database',
    'username',
    'password'
);
 
//The COUNT SQL statement that we will use.
$sql = "SELECT COUNT(*) AS num FROM users";
 
//Prepare the COUNT SQL statement.
$stmt = $pdo->prepare($sql);
 
//Execute the COUNT statement.
$stmt->execute();
 
//Fetch the row that MySQL returned.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
 
//The $row array will contain "num". Print it out.
echo $row['num'] . ' users exist.';

Tags:

Php Example