My codeigniter site stopped outputting data from my database - database

Good day internet. I am working on a basic cms using codeigniter. I have it set up so it is showing data from my database.
Here is the code in my controller for the first 2 pages
class Site extends CI_Controller {
public function index(){
$this->home();
}
public function home(){
$this->load->model("model_get");
$data["results"] = $this->model_get->getData("home");
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("content_home", $data);
$this->load->view("site_footer");
}
public function about(){
$this->load->model("model_get");
$data["results"] = $this->model_get->getData("about");
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("content_about", $data);
$this->load->view("site_footer");
}
Here is the model to get the data from the database
class Model_get extends CI_Model{
function getData($page){
$query = $this->db->get_where("pageData", array("page" => $page));
return $query->result();
}
}
Here is the view to output the data in the database
<div id="content">
<?php
foreach($results as $row){
$title = $row->title;
$text1 = $row->text1;
$text2 = $row->text2;
}
echo heading($title, 1);
?>
<p><?php echo $text1; ?></p>
<p><?php echo $text2; ?></p>
It has been working just fine but I wanted to use a form to change the data in the database. Here is the code for the view of my form
<div id="content">
<?php
$this->load->helper("form");
echo validation_errors();
echo form_open("site/updatevalues");
echo form_label("Heading", "title");
$data = array(
"name" => "title",
"id" => "title",
"value" => set_value("title"),
"style" => "width:100%",
"rows" => "rows:3"
);
echo form_textarea($data);
echo form_label("Text 1", "text1");
$data = array(
"name" => "text1",
"id" => "text1",
"value" => set_value("text1"),
"style" => "width:100%",
"rows" => "rows:3"
);
echo form_textarea($data);
echo form_label("Text 2: ", "text2");
$data = array(
"name" => "text2",
"id" => "text2",
"value" => set_value("text2"),
"style" => "width:100%",
"rows" => "rows:3"
);
echo form_textarea($data);
echo form_submit("dataSubmit", "Submit");
echo form_close();
?>
Here is the code snippet in my controller that is using the form inputs from the above view
public function updatevalues(){
$this->load->library("form_validation");
$this->form_validation->set_rules("title", "Heading", "required|xss_clean");
$this->form_validation->set_rules("text1", "Text 1", "required|xss_clean");
$this->form_validation->set_rules("text2", "Text 2", "required|xss_clean");
if($this->form_validation->run() == FALSE){
$data ["success"] = "";
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("data_input", $data);
$this->load->view("site_footer");
} else {
echo $data["success"] = "The page has been updated";
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("data_input", $data);
$this->load->view("site_footer");
$this->load->model("model_update");
$newRow = array(
"id" => "3",
"title" => set_value("title"),
"page" => "Contact Page", **<---This was the problem**
"text1" => set_value("text1"),
"text2" => set_value("text2")
);
$this->model_update->update1($newRow);
}
}
Here is the model that is handling updating the data in the database, I am just using the first function here
class Model_update extends CI_Model{
function update1($data){
$this->db->update("pagedata", $data, "id = 3");
}
function update2($data){
$this->db->update_batch("pagedata", $data, "id");
}
}
So after days of trying to figure this out I finally got it to update certain fields in the database which would theoretically update the output in the view but now it is giving me this error message:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: title
Filename: views/content_about.php
Line Number: 10
It is giving the error for all the variables I am trying to echo. I don't get it, I haven't touched the code to display from the database and now that I am finally able to change the data through a form the variable is all of a sudden undefined. If anyone can help me with this I would appreciate it. Been working on this single task for 2 weeks now!
Edit: As I was writing this up I figured out the problem and have put an arrow to identify it. The page data must be "about" because that is how the foreach loop is grabbing the data. I could just not post this but maybe this code will help someone else. Take what you can and enjoy internet you have just witnessed someone correcting themselves, lol.

Change this line in your site controller function home:
From this:
$data["results"] = $this->model_get->getData("home");
Into this:
$data["results"] = $this->model_get->getData("home page");
I know this because you took this from the youtube tutorial of Steven.

Related

Save associations not working in cakephp 4

I have these nested associations :
CustomRubriques hasOne ExtendedRubriques hasMany Photos
Photos has fields id and legend
I'm trying to save legend from CustomRubriques like this :
// CustomRubriques/edit.php
echo $this->Form->control('extended_rubrique.photos.0.id');
echo $this->Form->control('extended_rubrique.photos.0.legend');
echo $this->Form->control('extended_rubrique.photos.1.id');
echo $this->Form->control('extended_rubrique.photos.1.legend');
// etc..
// CustomRubriquesController.php
public function edit($id)
{
$rubrique = $this->CustomRubriques->findById($id)->firstOrFail();
if ($this->request->is(['post', 'put'])) {
$rubrique = $this->CustomRubriques->patchEntity($rubrique, $this->request->getData());
debug($rubrique); // $rubrique->extended_rubrique->photos[0]['id'] and $rubrique->extended_rubrique->photos[0]['legend'] are well defined
if ($this->CustomRubriques->save($rubrique, ['associated' => ['ExtendedRubriques', 'ExtendedRubriques.Photos']])) {
return $this->redirect(['action' => 'view', $rubrique->id]);
}
}
$this->set(compact('rubrique'));
}
The legend of the photos are not saved (without any error returned) and I really don't know why !
(Note that legend is true in Photo Entity's $_accessible )
Could anybody tell me what I'm doing wrong ?

Yii2 using array to build activeform - cannot get & echo second array element

I have created and registered a Yii2 component function 'formSchema' which
contains the array as such:
class FormSchema extends Component{
public function formSchema()
{
$fields = array(
['field' => 'username', 'controltype' => 'textinput'],
['field' => 'email', 'controltype' => 'textArea'],
);
return $fields;
}
}
?>
I call the array in the active form, however I cannot get the
['controltype'] using the same successful method as I do to retrieve ['field'] as
below. I would like to get that array element however seem unable to get any but the first level element:
<div class="usermanager-form">
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
$fields = $items = Yii::$app->formschema->formSchema();
foreach($fields as $field)
{
$field = $field['field'];
echo $form->field($model, $field);
}
?>
You may use array values in this way:
$fields = Yii::$app->formschema->formSchema();
foreach ($fields as $field) {
echo $form->field($model, $field['field'])->{$field['controltype']}();
}

Codeigniter form populate with db results not working

I have been trying for days now using the form class to populate the text fields from my database. I have also been searching to find out how to do it without any luck.
Please could somebody take a look at my code and tell me what I'm doing wrong.
Model
//This function brings up the selected users information for editing.
public function edit_user($id)
{
$this->db->select('id, email, name, lastname, homeaddress, posteladdress,
mobile, hometel, idnum');
$this->db->where('id', $id)->limit(1);
$query = $this->db->get('user');
return $query->result();
}
Controller
public function get_user_edit($id)
{
$this->load->helper('form');
$this->load->model('model_users'); //Load the user model
//Get the database results from the model
$data['results'] = $this->model_users->edit_user($id);
foreach ($data['results'] as $key => $row)
{
$data['results'] = array( 'id' => $row->id,
'email' => $row->email,
'name' => $row->name,
'lastname' => $row->lastname,
'homeaddress' => $row->homeaddress,
'posteladdress' => $row->posteladdress,
'mobile' => $row->mobile,
'hometel' => $row->hometel,
'idnum' => $row->idnum);
}
$this->load->view('edit_user', $data);
}
View
<div id="body">
<p>Edit user information.</p>
<?php
echo form_open('user_admin/user_update', $results);
echo validation_errors();
echo "<p><lable>Email:</lable>";
echo form_input('email', set_value('email'));
echo "</p>";
echo "<p><lable>Name:</lable>";
echo form_input('name', set_value('name'));
echo "</p>";
echo "<p>";
echo form_submit('edit_submit', 'Update');
echo "</p>";
echo form_close();
?>
I keep getting this error
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 1010
First thing. You're expecting a single row to be returned from the database, right? But you're looping through the result in your controller. Instead of doing that in your model:
return $query->result();
do this:
return $query->row();
and remove the foreach loop from your controller (it even has an unused $key var in there). You'll end up having cleaner and shorter code. Only if you're getting a single row, which seems to be the case.
Moving on.
Have you read the documentation here: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html ?
form_open('user_admin/user_update', $results); - what are you trying to do here?
You use the second parameter to pass attributes to the opening tag. Now looking at your code, your $results array has values for each field. Doesn't make much sense to push all this into the form opening tag, does it?
Field rendering with the correct values.
This is an example from the documentation how to configure and render an input field:
$data = array(
'name' => 'username',
'id' => 'username',
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%',
);
echo form_input($data);
So, your email input should be formatted having the minimal config like that:
$data = array(
'name' => 'email',
'value' => $results['email']
);
echo form_input('email', $data);
On validation (in your user_update() method in user_admin controller), you'll have to do some logic to capture the value you're validating. So you'll need something like:
$results['email'] = set_value('email');
Hope that makes sense!
Thank you very much for your help. I'm sure you must have realised that I'm new to Codeigniter, but with your help I was able to sort out the problem that I had.
I changed the query to return only the one result that it found like you suggested
return $query->row();
and you were right I didn't need the foreach loop to populate an array to pass to the view.
Thanks for pointing out that I was trying to pass the results from db as the attribute for the form.:)
I added my code below for anybody that come across my question with the same problem. Maybe it will help them.
My controller
public function get_user_edit($id)
{
$this->load->model('model_users'); //Load the user model
//Get the database results from the model
$data['results'] = $this->model_users->edit_user($id);
$this->load->view('edit_user', $data);
}
My model
//This fetches the selected users information for editing.
public function edit_user($id)
{
$this->db->select('id, email, name, lastname, homeaddress, posteladdress,
mobile, hometel, idnum');
$this->db->where('id', $id)->limit(1);
$query = $this->db->get('user');
return $query->row();
}
My view
<div id="container">
<h1>Edit user</h1>
<div id="body">
<p>Edit user information.</p>
<?php
echo form_open('user_admin/user_update');
echo validation_errors();
echo form_hidden('id', $results->id);
echo "<p><lable>Email:</lable>";
echo form_input('email', $results->email);
echo "</p>";
echo "<p><lable>Name:</lable>";
echo form_input('name', $results->name);
echo "</p>";
echo "<p><lable>Last name:</lable>";
echo form_input('lastname', $results->lastname);
echo "</p>";
echo "<p><lable>Home address:</lable>";
echo form_input('homeaddress', $results->homeaddress);
echo "</p>";
echo "<p><lable>Postal address:</lable>";
echo form_input('posteladdress', $results->posteladdress);
echo "</p>";
echo "<p><lable>Mobile number:</lable>";
echo form_input('mobile', $results->mobile);
echo "</p>";
echo "<p><lable>Home telephone:</lable>";
echo form_input('hometel', $results->hometel);
echo "</p>";
echo "<p><lable>ID number:</lable>";
echo form_input('idnum', $results->idnum);
echo "</p>";
echo "<p>";
echo form_submit('edit_submit', 'Update');
echo "</p>";
echo form_close();
?>
</div>

how to display result in view part in cakephp

public function outofstock(){
$this->loadModel('Store');
$store=$this->Store->find('all',array('fields' => array('Store.store_shortcode')));
$this->set('store',$store);
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$item=$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
foreach($item as $item1){
echo $item1['Item']['item_name'];
echo $store_shortcode;
}
endforeach;
$this->set('item',$item);
}
This is my controller part code .
I want to display echo $item1['Item']['item_name'] , $store_shortcode in view part . Actually in controller its displaying properly but in view part its not displaying . store_shortcode is GLF,DLLK,MKL . Item Name is ADASHG , GRAFGHJ, Store names or columns of item table and store_name of store table .
Controller ($items[ ]):
public function outofstock(){
$this->loadModel('Store');
$store=$this->Store->find('all',array('fields' => array('Store.store_shortcode')));
$this->set('store',$store);
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$items[] =$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
endforeach;
$this->set('items',$items);
}
In the view.ctp:
foreach($items as $item){
echo $item['Item']['item_name'];
}
But generally you have a a bad approach,
Do hasMany relational between the Store and Item model, and then easily with the help of a one query take data.
Use this in view file
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$item=$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
foreach($item as $item1){
echo $item1['Item']['item_name'];
echo $store_shortcode;
}
endforeach;

Trouble with my "Like" system

So, I'm adding a "Like" system to my CakePHP project and I have a little problem. When I want to add a Like ... it simply doesn't happen. Here is what I have :
<?php
echo $this->Form->create("Like", array("url" => array("controller" => "likes", "action" => "like")));
echo $this->Form->hidden("user_id",array(
"value" => AuthComponent::user("id")
));
echo $this->Form->hidden("post_id",array(
"value" => $post["Post"]["id"]
));
echo $this->Form->end();
echo $this->Html->link(
"<li><i class='icon-heart icon-large'></i> ".count($post["Like"])." likes</li>",
"",
array("escape" => false, "onclick" => "document.getElementById('LikeViewForm').submit();")
);
?>
And here is the controller :
<?php class LikesController extends AppController{
function like() {
$user_id = $this->Auth->user("id");
if(!$user_id){
$this->redirect("/");
die();
}
if ($this->request->is("post")) {
$d = $this->request->data;
$d["Like"]["id"] = null;
if($this->Like->save($d,true,array("post_id","user_id"))){
$this->redirect($this->referer());
}
}
}
}
And when I click the link, it refresh the page correctly, so I presume the form is send, but nothing new in the DB...
Any guess ?
For new record, you need use create() first. Try this:
function like() {
$user_id = $this->Auth->user("id");
if (!$user_id) {
$this->redirect("/");
die();
}
if ($this->request->is("post")) {
$this->Like->create();
if ($this->Like->save($this->request->data, true, array("post_id", "user_id"))) {
$this->redirect($this->referer());
}
}
}
Hope this helps.

Resources