PDO选择声明与MVC

时间:2016-02-24 20:53:57

标签: php pdo

” 我正在一个小型的MVC网站上工作,我遇到了一个小问题。我希望能够使用从我的数据库中提取的数据填充HTML选择下拉列表。我的Model类中的Select语句,我的View类中的标准HTML内容,我的控制器当前是空的,因为我有点混淆我应该添加到那里。

代码工作正常,没有错误。但是,我的观点呈现两次。

这是我的代码:

型号:

<?php
require_once('../Controller/config.php');

class AppCalc 
{
    public $dbconn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->dbconn = $db;
    }

    public function fillDropdown(){
        $stmt = $dbconn->prepare("SELECT Appliance FROM appliances");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

?>

查看:

<div id="appForm">

    <form id="applianceCalc">
        Typical Appliance: 
        <select name="appliances">
            <?php foreach($appliances as $appliance): ?>
            <option value="<?php echo $appliance['Appliance']; ?>">
                <?php echo $appliance['Appliance']; ?>
            </option>
            <?php endforeach; ?>
        </select>
        <br>

        Power Consumption:
        <input type="text"></input>
        <br>


        Hours of use per day:
        <input type="text"></input>
        <br>
    </div>
        <input type="submit" name="btn-calcApp" value="Calculate"></input>
        <input type="submit" name="btn-calRes" value="Reset"></input>

    </form>
    </div>

控制器:

   <?php
require_once('../Model/applianceModel.php');
require_once('../Tool/DrawTool.php'); 

$newCalc = new AppCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/applianceCalculator.php', array(
    'appliances' => $newCalc->fillDropdown()
));

echo $renderedView;

?>

我的配置文件:

<?php
class Database
{   
    private $host = "localhost";
    private $db_name = "energychecker";
    private $username = "root";
    private $password = "";
    public $dbconn;

    public function dbConnection()
    {

        $this->dbconn = null;    
        try
        {
            $this->dbconn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->dbconn;
    }
}
?>

这是我正在使用的表:

CREATE TABLE IF NOT EXISTS `appliances` (
  `AppId` int(11) NOT NULL AUTO_INCREMENT,
  `Appliance` varchar(50) NOT NULL,
  `PowerConsumption` int(8) NOT NULL,
  PRIMARY KEY (`AppId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

这是我目前看到的: http://i66.tinypic.com/30b31mx.jpg

任何帮助将不胜感激 谢谢!

1 个答案:

答案 0 :(得分:1)

模型函数fillDropdown应返回已获取行的数组,例如:

public function fillDropdown(){
    $stmt = $dbconn->prepare("SELECT Appliance FROM appliances");
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

然后,您必须以某种方式将数据传递给View。我建议构建一些类来渲染视图。这可以很简单:

class DrawTool
{        
    public function render($viewPath, array $context = array())
    {
        // start output buffering
        ob_start();

        // make variables with $key => value pairs from $context associative array
        // context will be gone after method execution thanks to variable scope
        extract($context);

        // render View
        include $viewPath;

        // return rendered View as string data type
        return ob_get_clean();
    }
}

现在,如果您有Draw类来渲染视图,您只需使用以下代码在Controller中绘制View:

require_once('../Model/applianceModel.php');
require_once('../Tool/DrawTool.php'); // or wherever else you plan to put this class

$newCalc = new AppCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/applianceView.php', array(
    'appliances' => $newCalc->fillDropdown()
));

echo $renderedView;

并且,在View文件中:

<div id="appForm">

    <form id="applianceCalc">
        Typical Appliance: 
        <select name="appliances">
            <?php foreach($appliances as $appliance): ?>
            <option value="<?php echo $appliance['id']; ?>">
                <?php echo $appliance['name']; ?>
            </option>
            <?php endforeach; ?>
        </select>
        <br>

        Power Consumption:
        <input type="text"></input>
        <br>


        Hours of use per day:
        <input type="text"></input>
        <br>
    </div>
        <input type="submit" name="btn-calcApp" value="Calculate"></input>
        <input type="submit" name="btn-calRes" value="Reset"></input>
</form>
</div>

在View文件中,您只需遍历$appliances数组(已提取的行),其中单$appliance是由数组表示的一行,例如idname个密钥。

最后有几个提示:

  • 不要使用?>标记结束纯PHP文件,因为在该标记之后的任何字符(最常见的是白色字符)将触发已发送标题的错误,如果您希望在之前设置一些标题 / strong>输出内容
  • 考虑使用fillDropdown方法检查某些值,因为失败方法$stmt->fetchAll()也可以在失败时返回 false