PHP / MySQL - 不断返回0

时间:2016-02-23 11:20:49

标签: php mysql pdo

嘿所以我正在尝试检索用户已经拥有多少个密钥以及他们的帐户允许拥有多少密钥,然后计算百分比并让它显示,而我知道下面的代码

$SQL1 = $odb -> prepare("SELECT `licenses` FROM `users` WHERE `username` = :username");
$SQL1 -> execute(array(':username' => $username));
$maxKeys = $SQL1 -> fetchColumn(0);

由于某种原因,以下代码继续返回0,即使表中有多个条目,我当前的用户为所有者

$SQL = $odb -> prepare("SELECT COUNT(*) FROM `licensetable` WHERE `owner` = $username");
$SQL -> execute(array());
$keysUsed = $SQL -> fetch(PDO::FETCH_ASSOC);

我知道它必须是如此简单的东西,但我无法理解我的生活。 表格结构如下

SELECT `id`, `key`, `owner` FROM `licensetable`

完整的原始页面来源

    <?php
    ob_start();
    require_once('include/db.php');
    require_once('include/initialize.php');
    if(!($user->LoggedIn())){
        header('location: login');
        die();
    }else{
        $username = $_SESSION['username'];
        $SQL = $odb -> prepare("SELECT COUNT(*) FROM `licensetable` WHERE `owner` = $username");
        $SQL -> execute(array());
        $keysUsed = $SQL -> fetch(PDO::FETCH_ASSOC);
        $SQL1 = $odb -> prepare("SELECT `licenses` FROM `users` WHERE `username` = :username");
        $SQL1 -> execute(array(':username' => $username));
        $maxKeys = $SQL1 -> fetchColumn(0);
        $keyPercentage = ($keysUsed / $maxKeys) * 100;
    }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQL</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
    <body>
        <div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header">Home</h1>
                </div>
            </div>
            <div class="row">
                <div class="col-md-9">
                    <?php echo $keyPercentage;
                    echo $maxKeys;
                    ?>
                </div>
            </div>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

尝试(已编辑)

返回页首 -

<?php
session_start();
ob_start();
require_once('include/db.php');

查询 -

$sql = "SELECT COUNT(*) as val FROM `licensetable` WHERE `owner` = :user");
$query = $odb->prepare($sql);
$query->bindValue(':user', $username);
$query->execute();

$keysUsed = $query->fetch(PDO::FETCH_ASSOC);
echo $keysUsed['val'];

当然可以在测试台上本地工作。