简体   繁体   中英

PHP count number of entries in a SQL table

I have a launch page that accepts emails. I am trying to count the total number of emails in the table. However, I am struggling to get it to work. The sql seems to be accurate, because I ran the sql script in phpmyadmin and it returned the correct value. However, when I do a var_dump of the variable that I assigned the sql script it does not return the correct value. Any suggestions?

PHP

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

PDO::exec() does not return results from a select statement - you should use PDO::query instead:

require(ROOT_PATH . "inc/database.php");
try {
    $query = $db->prepare("REPLACE INTO launch_email VALUES ('$email')");
    $query->execute();

    // dummy traversable - it'll only loop once
    for ($db->query("SELECT COUNT(email) AS cnt FROM launch_email") as $row) {
        print $row['cnt'];
    }
} catch (Exception $e) {
    echo "Data could not be submitted to the database.";
}
exit;
$editEmail = $db->query("SELECT COUNT(email) as email_count FROM launch_email");    
$fet = $db->fetch();

if($fet['email_count'] > 0)
{
   // Email exists
}
else
{
    // Email does not exist
}

I'm assuming $db is an instance of PDO .

The problem is that you are using the exec method of the PDO class, which simply returns the number of rows affected by the specified SQL query.

You will need to use the query method instead. That will return an instance of PDOStatement . If you call the fetchColumn method on this instance, you will get the desired result.

So I was able to figure it out...This is what I needed:

PHP

function get_count($count_id, $count) {

    $output = "";

    $output = $output . $count["email_count"];

    return $output;
}


try {
    $totalEmail = $db->query("SELECT COUNT(email) as email_count FROM launch_email");
} catch (Exception $e) {
    echo "Date could not be retrieved from database.";
    exit;
}
$countTotal = $totalEmail->fetchAll(PDO::FETCH_ASSOC);

foreach($countTotal as $count_id => $count) { 
    echo get_count($count_id,$count);
}
If you have to return count then you can use "print_r($editEmail)" also please check it.

Or try this one

$sql = "SELECT COUNT(email) FROM launch_email"; 
$result = $db->prepare($sql); 
$result->execute(); 
$number_of_rows = $result->fetchColumn(); 
echo $number_of_rows;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM