PHP计算SQL表中的条目数

时间:2014-04-14 18:06:55

标签: php sql

我有一个接受电子邮件的启动页面。我正在尝试计算表格中的电子邮件总数。但是,我正在努力让它发挥作用。 sql似乎是准确的,因为我在phpmyadmin中运行了sql脚本并返回了正确的值。但是,当我执行我为sql脚本分配的变量的var_dump时,它不会返回正确的值。有什么建议吗?

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;
}

5 个答案:

答案 0 :(得分:1)

PDO::exec()不会返回select语句的结果 - 您应该使用PDO::query代替:

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;

答案 1 :(得分:1)

$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
}

答案 2 :(得分:1)

我假设$dbPDO的实例。

问题是您正在使用exec类的PDO方法,它只返回受指定SQL查询影响的行数。

您需要使用query方法。这将返回PDOStatement的实例。如果您在此实例上调用fetchColumn方法,您将获得所需的结果。

答案 3 :(得分:1)

所以我能够弄清楚......这就是我所需要的:

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);
}

答案 4 :(得分:0)

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;