I created an input script. I write name and script post name into database. But I have error - ErrorException [ Notice ]: Undefined variable: result
.
There
You forgot to actually run your query:
public static function insert_names($name)
{
$query = DB::query(DATABASE::INSERT, 'INSERT INTO names (name) VALUES (:name)')->parameters(array(':name' => $name))->execute();
}
However it'd be a better approach to use Kohana's query builder:
public static function insert_names($name)
{
$query = DB::insert('names', array('name'))->values(array($name))->execute();
}
or, considering from your code I can judge you're a beginner, you can use ORM and simplify it even further by doing this directly in controller:
if(!empty($_POST['name']))
{
$result = ORM::Factory('index')->set(array('name' => $_POST['name']))->save();
}
However the problem will still exist because your insert_names method doesn't return anything so you'll be setting your template's result variable as FALSE.
I believe what you would like to do looks like this:
public static function insert_names($name)
{
if(DB::insert('names', array('name'))->values(array($name))->execute())
{
return $name;
}
}
(with ORM it wouldn't be necessary to create this method in the first place)
I see another error in your controller though - I guess you're not used to E_NOTICE errors. Rather than setting $result as empty string, it'd be better to simply refactor your code a little bit:
if(!empty($_POST['name']))
{
$this->template->content = View::factory('about/about');
if($name = Model::factory('index')->insert_names($_POST['name']))
{
$this->template->content->set('result', $_POST['name']);
}
else
{
// some kind of error message
}
}
It might be a good idea to group all these variables from template into one, nice family:
class Controller_About extends Controller_Template{
public function action_index()
{
$config = Kohana::$config->load('common');
$this->template->set(array(
'site_name' => $config->get('site_name'),
'site_description' => $config->get('site_description'),
'page_title' => 'About',
'styles' => 'index/index'
));
$this->template->content = View::factory('about/about');
if($name = Model::factory('index')->insert_names($_POST['name']))
{
$this->template->content->set('result', $_POST['name']);
}
else
{
// some kind of error message
}
}
}
There. Isn't that A LOT cleaner? :)
It could still use Validation though, but that doesn't cover your original question so I'll just leave it that way.