I have modelled and am now testing a Database for a PHP (CodeIgniter 4) web application. I made a function in my (products) Model that retrieves data from the DB and called that function in the controller.
getBasicInfo(int $id): array
{
$db = $this->connectToDB();
$query = $db->query('SELECT productName, productDescription, productType FROM konnektrix_db.products WHERE productID = $id LIMIT 1');
$row = $query->getRow();
return
[ $row->productName,
$row->productDescription,
$row->productType
];
}
}
class Home extends BaseController
{
public function index()
{
$ProductModel = new Products();
$data = $ProductModel->getBasicInfo(1);
//$data['name'] = 'Yuna';
return view('testing_view',$data);
}
}
What i want is to be able to access that data ($data) from my view (testing_view) but when i do, it doesn't recognise the variable. (refer to image for error)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Data testing view</title>
</head>
<body>
<h2>General product overview page</h2>
<h1><? $data; ?></h1>
</body>
Any idea on what i might be doing wrong?
I have looked at multiple sources on how to pass data from Controller to View in CI4, this is what they did unless i am missing something?
CodePudding user response:
When you pass an array to a view the array gets 'exploded' out.
So $data['name']
becomes $name
.
So just search for variables with the array keys as the names.
CodePudding user response:
According to documentation you should call the variable using the escape function.
Please try:
Adding string identifiers to the array from getBasicInfo function.
getBasicInfo(int $id): array
{
$db = $this->connectToDB();
$query = $db->query('SELECT productName, productDescription, productType FROM konnektrix_db.products WHERE productID = $id LIMIT 1');
$row = $query->getRow();
return
[ "name" => $row->productName,
"description" => $row->productDescription,
"type" => $row->productType
];
}
And then something like this in your view:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Data testing view</title>
</head>
<body>
<h2>General product overview page</h2>
<h1><? esc($name); ?></h1>
<h1><? esc($description); ?></h1>
<h1><? esc($type); ?></h1>
</body>