我正在一个小型网站上工作,我有点困惑一步。 我遵循一个非常简单的mvc模式,我现在有一个控制器创建一个会话数组,该数据包含表单已提交的所有发布的数据。这些数据来自几个不同的下拉框,它们都有不同的ID:
<?php
require_once('../Model/CalculatorModel.php');
require_once('../Tool/DrawTool.php');
$newCalc = new ConCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/calculator.php', array('calcvalues' => $newCalc->getValues()));
if(isset($_POST['btn-calcCon'])){
$_SESSION['post-data'] = $_POST;
$_SESSION['post-data']['heatingType'];
$_SESSION['post-data']['meterType'];
$_SESSION['post-data']['noBedrooms'];
$_SESSION['post-data']['houseType'];
$_SESSION['post-data']['houseAge'];
}
echo $renderedView;
?>
我的Model类中有一个select语句,它在WHERE子句中使用这些会话变量,如下所示:
<?php
session_start();
require_once('../Config/config.php');
class ConCalc
{
public $dbconn;
public $TypicalReading;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->dbconn = $db;
}
public function getValues () {
$stmt = $this->dbconn->prepare("SELECT Consumption FROM consumption
WHERE HeatingType = :heatType
AND MeterType = :meterType
AND Bedrooms = :noBeds
AND HouseType = :house
AND HouseAge LIKE :age");
$stmt->bindparam(":heatType", $_SESSION['post-data']['heatingType']);
$stmt->bindparam(":meterType", $_SESSION['post-data']['meterType']);
$stmt->bindparam(":noBeds", $_SESSION['post-data']['noBedrooms']);
$stmt->bindparam(":house", $_SESSION['post-data']['houseType']);
$stmt->bindparam(":age", $_SESSION['post-data']['houseAge']);
$stmt->execute();
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$TypicalReading = $result['Consumption'];
echo $TypicalReading; //used for testing
break;
}
}
}
?>
我在语句上做了一个Var_Dump,它确实打印出已发布的值:
array (size=8)
'gasUsed' => string 'Yes' (length=3)
'heatingType' => &string 'Electricity' (length=11)
'meterType' => &string 'Economy 7' (length=9)
'overnight' => string 'Yes' (length=3)
'noBedrooms' => &string '1 or 2' (length=6)
'houseType' => &string 'Flat' (length=4)
'houseAge' => &string 'More than 11' (length=12)
'btn-calcCon' => string 'Calculate' (length=9)
现在我表格的前两行如下:
HeatingType MeterType Bedrooms HouseType HouseAge Consumption
Gas Standard 1 or 2 Flat Less than 11 years 5430
Gas Standard 1 or 2 Flat More than 11 years 7270
如果我选择气体,标准,1或2,平面,小于11,那么在表格提交后,数字5430应显示在文本框中。
我有点不确定如何返回该值。我试图回显我的$ stmt变量,但它说PHP无法回显出一个PDO对象。
任何帮助将不胜感激 谢谢!
答案 0 :(得分:0)
试试这段代码:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
echo $result['gasUsed'].' '.$result['heatingType'] ;//...
编辑:
因此,如果您需要在结果中找到值(但我不知道为什么不使用where子句来过滤结果),请执行以下操作:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if( $result['gasUsed'] == 'Gas' && $result['heatingType'] == 'Standard' /* ... */ ){
$v = $result['Consumption'];
break;
}
}