codeigniter, passing object to view - php

I have the following in my codeigniter constructor:
$navbar= new stdClass();
$navbar->user_email = $this->user_email;
$navbar->vp = $this->vp;
When I try to access this in my index function:
public function index() {
var_dump($this->navbar);
this works.
I now tried to pass $this->navbar to the view with:
$this->load->view('buyers/navbar', $this->navbardata);
In the view I have
<?php echo 'in nav ';var_dump($this->navbar); exit; ?>
I get :
Message: Undefined property: MY_Loader::$navbar
How can I make this work?
Thanks in advance,

Try like this
$data['navbar'] = $this->navbardata;
$this->load->view('buyers/navbar', $data);
and in your view try like
<?php echo 'in nav ';var_dump($navbar); exit; ?>

First, create a controller like this
class Test extends CI_Controller
{
public function index()
{
$data['topics'] = "Views Testing";
$data['title'] = "Welcome To My Blog";
$data['myData'] = array("name" => "John Doe", "email" => "johndoe2020#gmail.com", "designation" => "CodeIgniter Developer");
$data['myObject'] = new MyClass("John Doe", "johndoe#gmail.com");
$this->load->view("blogview", array($data, "MySelf" => new MyClass("Doe John", "doejohn460#gmail.com"), "developer" => "Life at CodeIgniter Academy"));
}
}
class MyClass
{
public $name;
public $email;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
}
Now Create Your blogview.php File In views folder
And Add the following code to Access The Data Passed from Controllers
echo "<h3>Variables :</h3> ";
echo var_dump($title);
echo $title;
echo var_dump($topics);
echo $topics;
echo "<h3>Array :</h3> ";
echo var_dump($myData);
print_r($myData);
echo "<br><br>";
echo $myData['name'];
echo "<br>";
echo $myData['email'];
echo "<br>";
echo $myData['designation'];
echo "<br> <br>";
foreach ($myData as $data)
{
echo $data."<br>";
}
echo "<h3>Object </h3>";
echo var_dump($myObject);
echo "<br>";
echo $myObject->name;
echo "<br>";
echo $myObject->email;
echo "<br><br>";
echo $MySelf->name;
echo "<br>";
echo $MySelf->email;
echo "<br><br>";
foreach($myObject as $Object)
{
echo $Object."<br>";
}
echo "<h3>Array key:Value Pair</h3>";
echo $developer;
I hope this will help.

Related

Error code "Invalid argument supplied for foreach()" when using json_encode (oop, php)

I'm trying to create a to do list. When creating new posts it should encode the information to json and put the information in a json array. But somehow it seems the information isn't encoded correctly and when trying to print the posts I get the error message "Invalid argument supplied for foreach()". I just can't find where the mistake is.
I'm fairly new at this so to complex answers might be to hard for me to understand.
Edit:
Adding the whole freaking code. Something is seriously wrong. 🤦‍♀️
index:
<?php
spl_autoload_register(function ($class) {
include $class . '.class.php';
});
$allPosts = new Lista;
if(isset($_REQUEST['addNewPost'])){
$allPosts->addNewPost($_REQUEST['ett'], $_REQUEST['tva'], $_REQUEST['tre']);
}
?>
<?php $page_title = "Att göra lista";
include("includes/header.php");
?>
<?php
include("includes/sidebar.php");
?>
<h2>Min att göra lista</h2>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Uppgift: <input type="text" name="ett"/><br/>
Utfarare: <input type="text" name="tva"/><br/>
Senast: <input type="text" name="tre"/><br/>
<input type="submit" name="addNewPost" value="Lägg till post"/>
</form>
<?php
//Loopa igenom array
foreach ($allPosts->getTheList() as $key=>$val) {
echo "<section id='postPart'>" . $val->getEtt() . "<br/>" . $val->getTva(). " " . $val->getTre(). "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
}
//echo "<section id='postPart'>" . $_REQUEST['one'] . "<br/>" . $_REQUEST['two'] . " " . $_REQUEST['three'] . "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
var_dump($allPosts);
?>
</body>
</html>
Class: Lista:
<?php
class Lista{
public $theList=[];
function __construct(){
if(file_exists("text.json")>0)
$this->theList = json_decode(file_get_contents('text.json'), true);
}
function addNewPost($ett, $tva, $tre){
$posten = new Post ($ett, $tva, $tre);
array_push ($this->theList, $posten);
$jsonStr = json_encode($this->theList);
file_put_contents("text.json", $jsonStr);
}
function getTheList( ){
return $this->theList;
}
}
Class Post:
<?php
class Post{
public $ett;
public $tva;
public $tre;
function __construct ($ett, $tva, $tre){
$this->ett = $ett;
$this->tva = $tva;
$this->tre = $tre;
}
function getEtt():string{
return $this->ett;
}
function getTva(){
return $this->tva;
}
function getTre(){
return $this->tre;
}
}
Besides the typo, to json_encode an array of objects your need to make an exporter method which returns an array of each property or implement JsonSerializable
<?php
class Post implements JsonSerializable {
protected $whatIs = ' ';
protected $whoIs = ' ';
protected $whenIs = ' ';
function __construct($what,$who,$when){
$this->whatIs=$what;
$this->whoIs=$who;
$this->whenIs=$when;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$arr = [];
$arr[] = new Post(1,2,3);
echo json_encode($arr);
Result:
[{"whatIs":1,"whoIs":2,"whenIs":3}]
I think your problem is on this line:
$jsonStr = json_encode($this->$thePost, JSON_PRETTY_PRINT);
You might be trying to do this :
$jsonStr = json_encode($thePost, JSON_PRETTY_PRINT);
Since $thePost is an object, and not a property of your class. It could work if $thePost is a string that match a property name.

Variable set on true looses value after first if-statement ---?

This seems very bizarre to me.
At the beginning of my php-script I am defining a debug variable. In the script I am using this variable to test my functions etc. p.p. BUT:
After my first if-Statement, the variable $debug is not set on true but blank... what am I doing wrong:
Here is my code:
$debug=true;
if($debug){
echo 'Testausgabe: </br></br>';
include 'jsonData.php';
include 'database.php';
$ini_config=$ini_config = parse_ini_file("config.ini", true);
echo "Einbindung erfolgt!".LNBR;
$debug=true;
echo $debug;
echo LNBR;
}
function dropdownGen($link,$ini_config){
$drops=$ini_config['dropDowns'];
foreach($drops as $key => $liste){
$data=json_liste($link,$liste);
echo LNBR;
echo "droplist_parse=JSON.parse('".$data."');";
echo "ddslickNoImage(droplist_parse,'".$liste."');";
echo LNBR;
echo "ddslickNoImage_Toggle(droplist_parse,'".$liste."');";
echo LNBR;
}
}
function dropdownImgGen($link, $ini_config){
$images=$ini_config['image_links'];
print_r($images);
echo "<br><br>";
foreach($images as $key => $liste){
$link='..\\'.utf8_decode($liste);
echo $link;
echo LNBR;
$data=json_imageList($link);
echo $data;
echo LNBR;
echo "ddslickImageList(".$data.",'".$key."');";
}
}
if($debug){
echo $debug;
echo LNBR;
echo 'Testausgabe: </br></br>';
dropdownGen($link,$ini_config);
echo LNBR;
dropdownImgGen($link,$ini_config);
echo LNBR;
}

How to call a function in PHP

I have been following some courses on how to create a session object, which has worked out fine, If I place the complete code onto a PHP file, all works great!
What I would like to do is place this in another module (PHP file) and just use one line (or equivalent) to do this, such as GetSessiondata();
<?php
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
?>
You need to "require" your file, where you want to use it.
Here an example
Working with classes:
Whatever.php
class Whatever {
public function __construct() {
// Ever when the code is instantiated, this will be called too!
}
public function myMethod() {
echo 'hello';
}
}
index.php
require_once('./Whatever.php');
$whatever = new Whatever();
$whatever->myMethod();
Without classes:
functions.php:
function whatever(){ echo 'hello'; }
index.php:
require_once('./functions.php');
whatever();
Read more:
Require: http://php.net/manual/es/function.require.php
Require_once: http://php.net/manual/es/function.require-once.php
My advise is to split this refactoring process into 2 steps:
1.Wrap your code into function:
function someFunctionName() {
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
}
// and call your function
someFunctionName();
2.Create another file, let's say functions.php, in the same dir and move function into it. Now you can require this file inside your php page:
require_once 'functions.php';
// and call your function
someFunctionName();
I think you are looking for include
Save your file, and then you can include it in another file as:
include 'my_file.php';
You can also use:
include_once
require
require_once
Read the documentation for further explanations or see this question

The search result are all the data in the database instead of a specific data

When i go to the search box and type a specific roll number, it shows all the data in my database instead of the data that i have entered by roll number. i'm new to php and codeigniter.
Here's the Model:
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("stud", $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
public function get_results($search_term='default')
{
// Use the Active Record class for safer queries.
$this->db->select('*');
$this->db->from('stud');
$this->db->like('roll_no',$search_term);
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
}
?>
The Controller:
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->database(); //manual connection to the database
}
public function index() {
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('form');
$this->load->view('Stud_view',$data);
}
public function add_student_view() {
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student() {
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'mname' => $this->input->post('mname'),
'mobileno' => $this->input->post('mobileno'),
'email' => $this->input->post('email'),
'homeadd' => $this->input->post('homeadd')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'mname' => $this->input->post('mname'),
'mobileno' => $this->input->post('mobileno'),
'email' => $this->input->post('email'),
'homeadd' => $this->input->post('homeadd')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student() {
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function execute_search()
{
$this->load->model('Stud_Model');
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Use a model to retrieve the results.
$data['records'] = $this->Stud_Model->get_results($search_term);
// Pass the results to the view.
$this->load->view('result_view',$data);
}
}
?>
The View:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
Add
<br>
<?php
echo form_open('Stud_controller/execute_search');
echo form_input(array('roll_no'=>'search'));
echo form_submit('search_submit','Submit');
?>
</br>
<br>
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>First Name</td>";
echo "<td>Surname</td>";
echo "<td>Middle Name</td>";
echo "<td>Mobile/Telephone No.</td>";
echo "<td>Email Address</td>";
echo "<td>Home Address</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";
?>
<?php foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td>".$r->surname."</td>";
echo "<td>".$r->mname."</td>";
echo "<td>".$r->mobileno."</td>";
echo "<td>".$r->email."</td>";
echo "<td>".$r->homeadd."</td>";
echo "<td><a href = '".base_url()."stud/edit/".$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."stud/delete/".$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
</body>
</html>
And the result view of the search box:
<!DOCTYPE html>
<head>
<table border = "1">
<?php
echo "<tr>";
echo "<td>Roll No.</td>";
echo "<td>First Name</td>";
echo "<td>Surname</td>";
echo "<td>Middle Name</td>";
echo "<td>Mobile/Telephone No.</td>";
echo "<td>Email Address</td>";
echo "<td>Home Address</td>";
echo "<tr>";
?>
<?php foreach($records as $r) {
echo "<tr>";
echo "<td>".$r['roll_no']."</td>";
echo "<td>".$r['name']."</td>";
echo "<td>".$r['surname']."</td>";
echo "<td>".$r['mname']."</td>";
echo "<td>".$r['mobileno']."</td>";
echo "<td>".$r['email']."</td>";
echo "<td>".$r['homeadd']."</td>";
echo "<tr>";
}
?>
</table>
</head>
</html>
For example if I type 1 in the search box it will display all the data like this:
Sr# Roll No. First Name Surname Middle Name Mobile/Telephone No. Email Address Home Address
1 1 Charles Xavier Howlett 1234567891011 xaviercharles#gmail.com 9912 east street
2 2 Nancy Hopkins Johnson 09108873512 nancehp#gmail.com 3628 north street
instead of showing roll number one only.
You have a wrong parameter on your input search form, if you supply an array as a parameter, it will produce a name => value attribute pair.
So you could change the search form view to :
...
<?php
echo form_open('Stud_controller/execute_search');
echo form_input(array('name'=>'search'));
echo form_submit('search_submit','Submit');
?>
...

$this->form_validation->run() is working but validation_errors() return empty string

i know there are many question regarding this problem, but this case is little different ,
i have a main contoller name Hs_controller that run through out the application and i have 2 more controller Frontend_Controller , and Admin_Controller inheriting the Hs_Controller
class Hs_Controller extends CI_Controller {
public $data = array();
function __construct() {
parent::__construct();
$this->data["errors"] = array();
$this->data["site_name"] = config_item("site_name");
$this->data["meta_title"] = config_item("site_name");
$this->load->helper("form");
$this->load->library("session");
$this->load->library('form_validation');
}
}
the app im creating require login on frontend section too, so i import session and form_validation library in the Hs_Controller so i could use them throughout the application,
now the login Action looks like
public function login() {
$validation_rules = $this->user_r->rules;
$this->form_validation->set_rules( $validation_rules );
echo " form controllers : <br/>";
echo " validation :";
var_dump($this->form_validation->run());
echo "<br/>";
echo " errors :";
var_dump(validation_errors());
echo "<br/>";
echo " post :";
var_dump($_POST);
echo "<hr/>";
if ( $this->form_validation->run() == TRUE ) {
// we can login the user
}
$this->data["subview"] = "user/login";
$this->load->view("_layout_modal" , $this->data );
}
and the respective view is like
<?php
echo " form view : <br/>";
// echo " validation :";
// var_dump($this->form_validation->run());
// echo "<br/>";
echo " errors :";
var_dump(validation_errors());
echo "<br/>";
echo " post :";
var_dump($_POST);
echo "<hr/>";
?><div class="model-header">
<h3>Login</h3>
<p> hi user</p>
</div>
<div class="model-body"><?php
echo validation_errors();
echo form_open();
?><ul><?php
?><li><label>email</label><?php echo form_input("email"); ?></li><?php
?><li><label>password</label><?php echo form_password("password"); ?></li><?php
?><li><?php echo form_submit("submit" , "log in" , 'class="btn "'); ?></li><?php
?></ul><?php
echo form_close();
?></div>
the $this->form_validation->run() is working perfectly, and i can also see the $_POST form the view and controller but the validation_errors() alwasy return empty string ..
what i already tested
validation rules are working perfectly,
.htaccess solution on this link also didn't work
$_POST is not empty, i can be access from the controller and view as describe in this link
$this->form_validation->run() is also validation and working

Categories