How do I call the static method execute and use the $result array ?
i have this code:
<?php
$input_ = [
'object_id' => $id,
];
$results_wp_temp = ArticleLoadTagsData::execute($input_);
if (
is_array($results_wp_temp) &&
!empty($results_wp_temp)
) {
echo 'tags';
foreach ($results_wp_temp as $result_wp_temp) {
?>
<span><?php echo $result_wp_temp->name; ?></span>
<?php
}
} else {
echo 'no tags';
}
?>
and this class:
<?php
class ArticleLoadTagsData {
public static function execute($input = []) {
$result = [0=>1];
return $result;
}
}
Related
I got an error like this :
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: tasks
controller
public function show() {
$data['tasks'] = array();
$data['tasks'] = $this->Tasks_model->show_task()->result();
$this->load->view('pages/all', $data);
}
view
<?php
if( isset($tasks) && ( is_array($tasks) && count($tasks)>0 ) ) {
//echo"<pre>"; print_r($tasks); die();
for($i=0;$i<count($tasks);$i++)
{ ?>
<span><?php echo $task[0]['job']; ?></span><br />
<?php } ?>
<?php }
else { ?>
<span>No tasks records found.</span>
<?php } ?>
Model
public function show_task() {
return $this->db->get('task');
}
what's wrong with my code?
Controller
public function show() {
$this->$data['tasks'] = array();
$this->$data['tasks'] = $this->Tasks_model->show_task();
$this->load->view('pages/all', $data);
}
View
//Here, you can also use for loop to display data.
<?php
if( isset($tasks) && ( is_array($tasks) && count($tasks)>0 ) )
{
//echo"<pre>"; print_r($tasks); die();
for($i=0;$i<count($tasks);$i++)
{ ?>
<span><?php echo $task[0]['job']; ?></span><br />
<?php } ?>
<?php }
else { ?>
<span>No tasks records found.</span>
<?php } ?>
EDIT =>
Model
public function show_task() {
$query = $this->db->get('task');
if( $query->num_rows() > 0 ) //Always check you are getting result or not.
{
return $query->result_array(); //result_array() returns the query result as a pure array
}
else
{
return array();
}
}
Here you are returning return $this->db->get('task'); directly. So you are not getting anythingin View.
First you have to assign $this->db->get('task') to variable e.g. $query and pass result array to controller return $query->result_array();.
Reference => https://www.codeigniter.com/userguide3/database/results.html#result-arrays
Controller:
public function show() {
$data['tasks'] = array();
$data['tasks'] = $this->Tasks_model->show_task();
$this->load->view('pages/all', $data);
}
Model:
public function show_task() {
return $this->db->get('task')->result();
}
View Page:
<?php
if( isset($tasks) && ( is_array($tasks) && count($tasks)>0 ) )
{
//echo"<pre>"; print_r($tasks); die();
for($i=0;$i<count($tasks);$i++)
{ ?>
<span><?php echo $task[0]['job']; ?></span><br />
<?php } ?>
<?php }
else { ?>
<span>No tasks records found.</span>
<?php } ?>
I'm new to PDO and I am converting to it from MySQLi due to recent issues I've been having with my web space.
I am trying to use FETCH_ASSOC to loop through results to get the individual records produced by my query, however, the loop is never ending and continuously repeats the first record in the results over and over again. Any suggestions?
<?php
$Request = databaseManager::getDB()->prepareSQL("SELECT Username, 2Wins, 2Loses, (2Wins/(2Wins+2Loses))*100 as WinRate FROM tblUsers ORDER BY 4 DESC");
//$LstResults = $Request->fetchAll();
while($LstResults = $Request->fetchArray()){
if($LstResults["WinRate"] >= 50){ ?>
<tr>
<td><?php echo $LstResults["Username"]; ?></td>
<td>
<div class="progress progress-xs">
<div class="progress-bar progress-bar-success" style="width: <?php echo $LstResults["WinRate"]; ?>%"></div>
</div>
</td>
<td><span class="badge bg-green"><?php echo intval($LstResults["WinRate"]); ?></span></td>
</tr>
<?php }
} ?>
Class
class databaseManager{
protected $dbHND;
protected $currentSQLStatement;
protected $bind;
private $StrDBHost='localhost';
private $StrDBPort = "3306";
private $StrDBUser='thomassm_sqlogin';
private $StrDBPass='password';
private $StrDBName='thomassm_CadetPortal';
public function __construct(){
if ($this->dbHND = new PDO ('mysql:host=' . $this->StrDBHost . ';dbname=' . $this->StrDBName . ';port=' . $this->StrDBPort, $this->StrDBUser, $this->StrDBPass)){
$this->bind = null;
}
else{
return false;
}
}
static public function getDB(){
$tmpInstance = new self ();
return $tmpInstance;
}
public function prepareSQL($sqlQueryString = null){
if ($sqlQueryString === null){
$this->currentSQLStatement === false;
return false;
}
elseif (is_array ( $sqlQueryString )){
if ($this->currentSQLStatement = $this->dbHND->prepare ( $sqlQueryString [0] )){
$this->bind = $sqlQueryString [1];
return $this;
}
else{
throw new \Exception ( "Could not prepare SQL Statement, " . print_r ( $this->dbHND->errorInfo () ) );
return false;
}
}
else{
if ($this->currentSQLStatement = $this->dbHND->prepare ( $sqlQueryString )){
return $this;
}
else{
throw new \Exception ( "Could not prepare SQL Statement, " . print_r ( $this->dbHND->errorInfo () ) );
return false;
}
}
}
public function fetchArray(){
if (! $this->currentSQLStatement){
return false;
}
elseif ($this->bind != null){
$this->currentSQLStatement->execute ( $this->bind );
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
else{
$this->currentSQLStatement->execute ();
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
}
public function fetchAll(){
if (! $this->currentSQLStatement){
return false;
}
elseif ($this->bind != null){
$this->currentSQLStatement->execute ( $this->bind );
return $this->currentSQLStatement->fetchAll ( PDO::FETCH_ASSOC );
}
else{
$this->currentSQLStatement->execute ();
return $this->currentSQLStatement->fetchAll ( PDO::FETCH_ASSOC );
}
}
}
As KIKO Software said in the comments to the questions, I need to only run execute once otherwise it will reset the count of the loop. I have removed the executing from the fetchArray code and now call it before calling fetchArray, like so:
public function fetchArray(){
if (! $this->currentSQLStatement){
return false;
}
else{
return $this->currentSQLStatement->fetch ( PDO::FETCH_ASSOC );
}
}
There is an error message when my view is being loaded. "Call to a member function result() on a non-object"
How do I fix this?
This is the loop in my View: discussion/view.php
<?php foreach ($query->result() as $result) : ?>
<tr>
<td>
<?php echo anchor('comments/index/'.$result->ds_id,$result->ds_title) . ' '
. $this->lang->line('comments_created_by') . $result->usr_name; ?>
<?php echo anchor('discussions/flag/'.$result->ds_id,
$this->lang->line('discussion_flag')) ; ?>
<br />
<?php echo $result->ds_body ; ?>
</td>
</tr>
<?php endforeach ; ?>
and this is the function index in my Comments Controller:
public function index() {
if ($this->input->post()) {
$ds_id = $this->input->post('ds_id');
} else {
$ds_id = $this->uri->segment(3);
}
$page_data['discussion_query'] = $this->Discussions_model->fetch_discussion($ds_id);
$page_data['comment_query'] = $this->Comments_model->fetch_comments($ds_id);
$page_data['ds_id'] = $ds_id;
$this->form_validation->set_rules('ds_id', $this->lang->line('comments_comment_hidden_id'), 'required|min_length[1]|max_length[11]');
$this->form_validation->set_rules('comment_name', $this->lang->line('comments_comment_name'), 'required|min_length[1]|max_length[25]');
$this->form_validation->set_rules('comment_email', $this->lang->line('comments_comment_email'), 'required|min_length[1]|max_length[255]');
$this->form_validation->set_rules('comment_body', $this->lang->line('comments_comment_body'), 'required|min_length[1]|max_length[5000]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('common/header');
$this->load->view('nav/top_nav');
$this->load->view('comments/view', $page_data);
$this->load->view('common/footer');
} else {
$data = array('cm_body' => $this->input->post('comment_body'),
'usr_email' => $this->input->post('comment_email'),
'usr_name' => $this->input->post('comment_name'),
'ds_id' => $this->input->post('ds_id')
);
if ($this->Comments_model->new_comment($data)) {
redirect('comments/index/'.$ds_id);
} else {
// error
$this->data['message'] = 'Error!';
}
}
}
i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more ยป </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"
I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';