D
D
Denis Davydenko2017-08-31 16:50:18
MySQL
Denis Davydenko, 2017-08-31 16:50:18

How to fetch data from database when using Smarty?

Good afternoon.
I am learning to work with Smarty 3.
Due to the lack of an example in Google of the structure I need, which would help me understand the moment indicated in the title, I ask you to give me 10 minutes.
I will clarify once again - there are many examples, but I did not find the structure I needed (to make it clear).
Therefore, I ask you to make me a concrete example according to my conditions.
There is a DB "base", in it the table "table" with columns "col1", "col2", "col3". Located on localhost, connection data root, 123456.
Index.php code

<?php
include 'configs/config.php';
***
$smarty->assign('col1', $row);
$smarty->assign('col2', $row);
$smarty->assign('col3', $row);
$display = $smarty->display('index.tpl');

config.php code
<?php
$mysqli = new mysqli("localhost", "root", "123456", "base");
$mysqli->set_charset("utf8");
if (mysqli_connect_errno()) {
    printf("Ошибка соединения: %s\n", mysqli_connect_error());
    exit();
}
define('SMARTY_DIR', '/usr/share/php/smarty3/');
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();

index.tpl code
<html>
    <head>
        <title>Главная</title>
        <meta charset="utf-8" />
    </head>
    
    <body>
Значение столбца col1 {$col1}.
Значение столбца col2 {$col2}.
Значение столбца col3 {$col3}.
    </body>
</html>

Please describe what code needs to be added instead of *** in order for this example to work.
I can't figure out the structure myself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Ivasik, 2017-09-04
@GooseTheDestroyer

Just look at the template engine for data, it cannot fetch data from the database, this is beyond its responsibility. In your case, you must first execute a query that will return you 1 record from the database (using a pre-created mysqli connection), then specify this data in $smarty->assign (in general, assign actually attaches a variable to the template, the first parameter is the name of this variable in template, the second is its value, which should be displayed there).
If you make it more universal - you can pull 1 record from the database, get it as an assoc array and do something like this:

$row = //код выборки записи из базы//;

foreach ($row as $column => $value) {
        $smarty->assign($column, $value);
}

this way you will dynamically assign the columns from the record in the database as variables to the template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question