John Davidson

php - Use return data from one function in another and pass it to Smarty template

0 comments
Message:


What I'm trying to do is to have one datatable probably as a template and passing different datas on different pages.


Example functions.php


function force() {
global $DBconn;
$q = "SELECT * FROM table";
$res = $DBconn->query($q);

return $this->result;
}

function force_1() {
global $DBconn;
$q = "SELECT * FROM table_1";
$res = $DBconn->query($q);
return $this->result;
}

function table() {

echo '
<table class="sortable">
<thead>
<tr>
<th>
Title
</th>
</tr>
</thead>
<tbody>';
foreach ($this->result as $key) {
echo ' <tr>
<td>
$key->name
</td>
</tr>';
}
echo '</tbody>
</table>';
}
return true;
}

Then in the page.php


$table = table();
$smarty->assign("table", $table);

and page.tpl


<div> {$table} </div>

Currently nothing showed on page, not even an error or something. So:



  1. Is this the way that should be done? With using the returned result in either function and then pass it to the smarty template?



My Answer:
No, the way you are trying to use the returned result in the `table()` function and then pass it to the Smarty template is not correct.

You should modify your functions.php file to properly handle the returned result and pass it to the Smarty template. Here is an updated version of your functions.php file:

php
function force() {
global $DBconn;
$q = "SELECT * FROM table";
$res = $DBconn->query($q);

return $res->fetchAll();
}

function force_1() {
global $DBconn;
$q = "SELECT * FROM table_1";
$res = $DBconn->query($q);
return $res->fetchAll();
}

function getTableData() {
$data = force(); // You can change this to force_1() if needed
return $data;
}


Then in your page.php file, you can call the `getTableData()` function and assign the result to the Smarty template:

php
$tableData = getTableData();
$smarty->assign("tableData", $tableData);


And in your page.tpl file, you can loop through the `$tableData` array to display the table:

html







{foreach $tableData as $row}



{/foreach}

Title
{$row.name}



This way, you are properly fetching the data in the `getTableData()` function and passing it to the Smarty template for display.

Rate this post

4 of 5 based on 8374 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us