未定义变量:data in my view
这是一个简单的显示数据的输入。
那么,为什么这个输入不显示我的查询结果呢?我认为
<input type="text" name="sitename" value="<?php echo $data['sitename']; ?>"><br>
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
$num = mysqli_num_rows($sqli);
while ($num > 0)
{
$data = mysqli_fetch_array($sqli);
$num--;
}
return $data;
}
}
仅仅因为变量在某处声明,并不意味着它在任何地方都可用。所有变量都有可访问的scope
。有关范围的更多信息,请参阅:http://php.net/manual/en/language.variables.scope.php。
您需要将$data
变量传递到视图中。我想象你在使用某种MVC框架因为你有一个模型和一个视图。如果是这种情况,您可以查找如何将变量传递到特定框架中的视图。控制器方法的基本结构可能是这样的:
//sudo code - not specific to an actual framework
public function controller_method()
{
$data = $model->getData();
$this->template->set('data',$data);
$this->template->load('view');
}
只需搜索如何在您的特定框架中做到这一点。希望这对你有帮助!
编辑根据你的评论,看起来你在加载视图的之后设置了data 。您需要交换顺序并在之前调用$display = new Display("main"); $data = $display->getData();
include'../model/display.php';
如果查询返回0行,您的while()
循环将永远不会执行,因此它不会设置$data
。
因为你只从查询返回1行,你不需要一个循环,你可以只使用if
。然后,只有当它成功时,才能返回$data
。
public function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY 'id' DESC LIMIT 1";
if (!$sqli = mysqli_query($this->cxn->connect(),$query))
{
throw new Exception("Error Processing Request");
}
else
{
if ($data = mysqli_fetch_array($sqli))
{
return $data;
}
else
{
return null;
}
}
}