根据数据库条目显示或隐藏复选框

时间:2015-05-12 15:21:10

标签: php mysql

我想要一个复选框只出现在数据库中有'Y'的情况下,我该怎么做呢?

这是我想出的,我也尝试了很多其他方法......

<form name="Discount" id="COTCode" action="cart.php" method="POST">
    <input type="checkbox" name="COTCode" id="COTCode" onclick="this.form.submit();"
</form>
Automatic discount check
<?php

    $sql  = "SELECT COTCode FROM stock";

    if ($COTCode == 'Y') {

        echo "You can recieve discount";

    } else if ($COTCode == 'N') {

        echo "Sorry this article doesn't come with discount";

    }

?>

1 个答案:

答案 0 :(得分:1)

首先,从数据库中提取一些内容:

$db = new PDO('mysql:dbname=yourDBName;host=yourHost;',$username,$password);
$sql = <<<SQL
SELECT COTCode FROM stock
WHERE whatever_conditions
SQL;
$query = $db->prepare($sql);
$query->execute();
$costCodes = $query->fetchAll(PDO::FETCH_ASSOC);

然后,您希望循环显示结果并根据需要打印HTML。

foreach($costCodes as $code){
    if($code['COTCode'] === 'Y') print 'You can receive a discount.';
    else print 'Sorry, this article doesn\'t come with a discount';
}

如果您只期待一个结果,则上述变化不大。您只需使用$query->fetchAll,而不是$query->fetch。然后循环变得不必要了:

$costCode = $query->fetch(PDO::FETCH_ASSOC);

if($costCode['COTCode'] === 'Y') print 'You can receive a discount.';
else print 'Sorry, this article doesn\'t come with a discount.';