ziko0 ziko0 - 3 months ago 10
PHP Question

the data do not display in my view

Undefined variable: data in my view

This is a simple display data in the input.

So, why this input isn't display my query result at it?

my view

<input type="text" name="sitename" value="<?php echo $data['sitename']; ?>"><br>


model

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;
}
}

Answer

Simply because a variable is declared somewhere, doesn't mean it is available everywhere. All variables have scope in which they are accessible. See this: http://php.net/manual/en/language.variables.scope.php for more information on scope.

You need to pass the $data variable into your view. I image you're using some sort of MVC framework since you have a model and a view. If this is the case you can lookup how to pass variables into views in that specific framework. The basic structure of your controller method might look something like this:

//sudo code - not specific to an actual framework
public function controller_method() 
{
  $data = $model->getData();
  $this->template->set('data',$data);
  $this->template->load('view');
}

Just search how to do that in your specific framework. Hope that helps!

EDIT Base on your comment it looks like you're setting data after you load the view. You need to swap the order and call $display = new Display("main"); $data = $display->getData(); before you include'../model/display.php';