Pass data from a class to a template - php

I don't know how to pass data from a class to one of my class to the studentShow template file.
MODEL
<?php
class Student{
public function all(){
require_once('config/db.php');
$SQLCommand = "SELECT * FROM people";
$Query = $conn->prepare($SQLCommand);
$Query->execute();
$rows = $Query->fetchAll(PDO::FETCH_OBJ);
return $rows;
}
}
?>
index
<?php
require_once("app/Controller/StudentController.php");
$Student = new StudentController();
$Student->index();
?>
Controller
<?php
require_once("app/Student.php");
class StudentController{
public function index(){
$Student = Student::all();
include ('resource/studentShow.php');
}
}
?>
My Question is: in my Controller how to pass that $student variable to studentShow.php.

Here is the way to achieve that:
public function index() {
$student = Student::all();
extract(['student' => $student]);
ob_start();
include ('resource/studentShow.php');
return ob_get_clean();
}
Read more about ob_start, extract & ob_get_clean

Related

php mysql foreach repeats twice

Hi i am using foreach in php oops to output data from the mysqlbut each data outputs twice please check my code and help it i have tried but no correct result
Here is the code below i have used
class getdata extends db{
public function getdata(){
$sql = "SELECT * FROM users";
$results = $this->connect()->query($sql);
$numrows = $results->num_rows;
if($numrows > 0){
while($row = $results->fetch_assoc()){
$data[] = $row;
}
return $data;
}
else{
echo 'no values';
}
}
}
class showusers extends getdata{
//show users
public function showusers(){
$datas = $this->getdata();
foreach($datas as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->showusers();
Don't give your function the same name as your class.
With $showusers = new showusers(); you are already executing the showusers function.
To cite php.net:
For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.
Source:https://www.php.net/manual/en/language.oop5.decon.php
So your function showusers() is treated as a constructor for your showusers class and therefore is executed twice. Once when you create an object of the class and once when you call the method.
your code is a bit convoluted I'd suggest passing the database connection object rather than extending continiously.
In this case your constructor showUsers() outputs a list of users. therefore it repeats because you are calling this function twice.
$showusers = new showusers(); // prints users
$showusers->showusers(); // prints users again
move your display function
class showusers extends getdata{
$data;
//initialize
public function showusers(){
$this->data = $this->getdata();
}
//show users
public function displayUsers(){
foreach($this->data as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->displayUsers();

Common SQL query in Zend-Framework

How i can use a sql-query code that i already have on Zend-Framework using Model and Controller?
I'm tried of many ways and i can't solve this.
This is a example of "common sql-query code" to test:
"SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100"
*My original code it's a big query and it's terrible transform to a zend-select()
This is my Model:
class PedidosInscricoesModel extends Zend_Db_Table_Abstract{
protected $_name = 'sa_arquivos_retorno';
public function getPedidosInscricoes(array $params) {
$this->_db = Zend_Registry::get('db2');
$session = new Zend_Session_Namespace('autenticacao');
$query = $this->query("SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 100");
$retorno = $this->fetchAll($query)->toArray();
return $retorno;
}}
And That's my Controller:
public function indexAction()
{
$PedidosInscricoesModel = new PedidosInscricoesModel();
$this->view->id_arquivos_retorno = $_REQUEST['id_arquivos_retorno'];
$params = $this->_request->getParams();
$data = $PedidosInscricoesModel->getPedidosInscricoes($params);
$this->view->data = $retorno;
}
My index view:
<?php
foreach($this->data as $dados) {
?>
<tr>
<td><?php echo $dados["id_arquivos_retorno"]; ?></td>
</tr>
<?php
}
?>
-Sorry for bad english guys
I got it!
Just modifying the Model using "zend_db_statement" in this way:
class PedidosInscricoesModel extends Zend_Db_Table_Abstract{
public function getPedidosInscricoes()
{
$db = Zend_Registry::get('db2');
$sql = "SELECT id_arquivos_retorno FROM sa_arquivos_retorno LIMIT 20";
$stmt = $db->query($sql);
$retorno = $stmt->fetchAll();
return $retorno;
}
}

How to fetch title of an item from a database and send it to the header template in CodeIgniter

I am writing an application in CodeIgniter where I specify the <title> meta-tag on every page in every controller which I have managed to send to my header template. However, now I have created an application that fetch credit cards and their titles from the database, through an CodeIgniter model. I would like to automatically fetch and use the credit card's name in <title> so that i don't need to change it manually, but I'm a little stuck on how to proceed.
This is my code as of now:
Controller
public function show($card = NULL)
{
$data['query'] = $this->Listing_model->get_card($card);
$header["page_title"] = from the model
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
Model
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query->result();
}
I have been following the official CodeIgniter documentation when creating this application, but so far no luck. Any solutions?
Try this
Model is changed
Controller is changed.
In Model
function get_card($card)
{
$query = $this->db->query("SELECT * FROM table_name WHERE creditcards = '$card' ");
$result = $query->result_array();
$count = count($result); # New
if(empty($count)){ # New
return FALSE;
}
elseif($count > 1){ # New
return 0;
}
else{
return $result;
}
}
In Controller
public function show($card)
{
$result = $this->Listing_model->get_card($card); # Changed
if($result == FALSE){ # New
echo "No Data Found";
}
elseif($result == 0){ # New
echo "Multiple Data Found";
}
else{
$data["page_title"] = $result[0]['field_name']; # Changed
$this->load->view('includes/header',$data); # Changed
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
In View
<?php echo (!empty($page_title)) ? $page_title : ''; ?> # Changed
A simple example:
Controller
$query = $this->Listing_model->get_card($card);
$query = $query->row();
$header["page_title"] = $query->title;
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
You can create a Base Controller and Extends all you other controller to that base controller.
Like this
<?php
class MY_Controller extends CI_Controller {
public $data = array();
function __construct() {
parent::__construct();
$this->data['errors'] = array();
$this->data['site_name'] = config_item('site_name');
}
}
Then In Your Controller
class Test extends MY_Controller
{
function __construct() {
parent::__construct();
$this->data['meta_title'] = 'Your Title';
}
}
And in you views access the page title like this:
echo("<title>.$site_name.</title>");
Create a base controller. The default location for this is application/core/MY_Controller.php => this can be changed via the config.
By using $this->site_data you can add variables in your base class and use them in every controlle/view
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('your model');
$result = $this->Listing_model->get_card($card);
$this->site_data['query']=$result;
$this->site_data_header["page_title"] = $result['get the property you want'];//this is possible, as get_card returns 1 result
}
}
class YourClass extends MY_Controller
{
function __construct()
{
parent::__construct();
}
public function show($card = NULL)
{
//you don't need to split the variables
//for header and the rest
$this->load->view('includes/header',$this->site_data_header);
$this->load->view('listings/listing_card',$this->site_data);
$this->load->view('includes/footer');
}
}
And I think your get_where is wrong:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
your limit is 0
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 1,0);//limit 1 offset 0
return $query->result();
}
access the data in your view
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Controller
$card_data= $this->Listing_model->get_card($card); //Your model returns an array of objects
$header["page_title"] = $card_data[0]->title; //grab value of 'title' property of first object returned from model.
$this->load->view('includes/header',$header);
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Try this:
function get_card($card = FALSE)
{
$data = $this->db->get_where('creditcards', array('slug' => $card), 0,1)->result();
$data->title = $data[0]->title;
return $data;
}
Controller
$query = $this->Listing_model->get_card($card);
var_dump($query);
//Your $query may be some data got from db;
$card_name = "";
if(!empty($query)){
$card_name = $query[0]->name; //You must verify the name attribute and it should in the $query result;
}
$header["page_title"] = $card_name;
View
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
You may need to create some routes for your show function. Codeigniter URI Routing
$route['your_controller_name/show/(:any)'] = 'your_controller_name/show/$1';
I am not sure if you have set up a htaccess for your main directory so you could remove the index.php from your url.
Try this code below
Model:
<?php
class Listing_model extends CI_Model {
function get_card_title($card) {
$this->db->where('slug', $card);
$query = $this->db->get($this->db->dbprefix . 'creditcards');
if ($query->num_rows() > 0) {
$row = $quer->row();
return $row->title;
} else {
return false;
}
}
}
Controller: Your_controller_name.php
<?php
class Your_controller_name extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('listing_model');
}
public function show($card) {
$data['title'] = $this->listing_model->get_card_title($card);
$this->load->view('includes/header', $data);
$this->load->view('listings/listing_card', $data);
$this->load->view('includes/footer');
}
}
View:
<head>
<title><?php echo $title;?></title>
</head>
In your listing card view, do this:
foreach ($query as $rec){
<title><?php echo $rec->title ?></title>
}
replace 'title' with the name of the column on your database that keeps the title of the credit card...so you are passing the results of the query you ran in your controller to this view, and then using a foreach loop to display data of the specific credit card
You can use template library for robustness and use as follows:
Controller
$this->template->title('Home :: ' . $this->data['metadata']['site_name'])
->set_layout('home_layout')
->build('listing_card', $this->data);
Views
<title><?php echo $template['title']; ?></title>
<?php echo $template['metadata']; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Reference: https://github.com/philsturgeon/codeigniter-template
Just to add another, there's no reason this shouldn't work:
$data['query'] = $this->Listing_model->get_card($card);
$this->load->view('header', array('page_title' => $data['query'][0]->column_name));
//Will there only be one result? Consider returning $query->row(). Multiple,
//loop through and set one title
In your view:
<title><?=isset($page_title) ? $page_title : "";?></title>
If this doesn't work your query isn't returning what you think it is.
Controller :
$data["page_title"] = $result[0]['title_field'];
view:
and You just need to write in your header file like :
<title><?php echo $page_title; ?></title>
In your model - don't return $query->result(), just return $query:
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query;
}
Controller:
public function show($card = NULL)
{
// verify that you got something back from the database
// or show an error
if( ! $query = $this->Listing_model->get_card($card) )
{
$this->_showNoResultsFor($card) ;
}
else
{
// get one record from the query using row()
$onecard = $query->row() ;
// assign the title using whatever your field name is called
$header["page_title"] = $onecard->thetitle ;
// Now assign the query result() to data
$data['query'] = $query->result() ;
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
I call the parent constructor as I extend new controllers from CI_Controller and MY_Controller so that I can enjoy higher variable declarations that are shared throughout the project.
I recommend creating general use model methods so that they have greater utility and can be re-used by many controllers in your project.
To make it easier to load header data into all controllers in your project, I recommend declaring some default header data in MY_Controller then within lower level controllers, you can amend that data and pass it to the view(s).
ci/application/core/MY_Controller.php
<?php
/**
* #property Listing_model ListingModel
* #property CI_DB_query_builder|CI_DB_postgre_driver $db
* #property CI_Loader $load
* #property CI_Config $config
*/
class MY_Controller extends CI_Controller
{
protected $headerData;
public function __construct()
{
parent::__construct();
$this->headerData['title'] = 'Some Default Title';
$this->headerData['js'] = [
'loaded_unconditionally.js',
];
$this->headerData['css'] = [
'loaded_unconditionally1.css',
'loaded_unconditionally2.css',
];
}
}
ci/application/controllers/Listing.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Listings extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Listings_model', 'ListingsModel');
}
public function show(string $card): void
{
$listing = $this->ListingModel->getByCard($card);
$this->headerData['title'] = $listing->name ?? 'Invalid Card Provided';
$this->load->view('layout/header', $this->headerData);
$this->load->view('listings/listing_card', ['listing' => $listing]);
$this->load->view('layout/footer');
}
}
ci/application/models/Listings_model.php
// returns object or null
function getByCard(string $card): ?object
{
// it is assumed that the slug column will be UNIQUE
return $this->db->get_where('creditcards', ['slug' => $card])->row();
}
// returns empty array or array of objects
function get(?int $limit, int $offset = 0): array
{
$args = ['creditcards'];
if ($limit !== null) {
array_push($args, $limit, $offset);
}
return $this->db->get_where(...$args)->result();
}
ci/application/views/layout/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $title; ?></title>
<?php foreach ($css as $filepath) { ?>
<link rel="stylesheet" href="<?php echo base_url("assets/css/$filepath"); ?>" />
<?php } ?>
<?php foreach ($js as $filepath) { ?>
<script src="<?php echo base_url("assets/js/$filepath"); ?>" />
<?php } ?>
</head>
ci/application/views/listings/listing_card.php
<?php
/**
* #var object|null $listing
*/
// start crafting your html markup and reference $listing as needed
if (!empty($listing->name)) {
echo "<p>Hello $listing->name</p>";
} else {
echo "<p>Um, who are you again?</p>";
}

How To Set character_limiter() in Codeigniter

I'm new to Codeigniter. Now I want to set the character limit in the view. First, get the data from the database with $query_result->result(), and then show it in the view using foreach().
Here is my Controller, Model and View:
public function index() {
$data = array();
$data['category'] = $this->product_model->selectAllcategory();
$data['randProduct'] = $this->product_model->selectRandomProduct();
$data['products'] = $this->product_model->selectAllProduct();
$data['maincontent'] = $this->load->view('home', $data, true);
$data['title'] = 'Welcome Russel Store';
$this->load->view('index', $data);
}
And my Model:
public function selectAllProduct() {
$this->db->select('*');
$this->db->from('product');
$this->db->where('status', 1);
$this->db->order_by('product_id', 'desc');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
And I want to set the character limit in the View:
http://russelstore.mastersite.info
echo character_limiter($result->product_title, 25);
http://ellislab.com/codeigniter/user-guide/helpers/text_helper.html
You should import Text Helper
in your controller, it is a good practice to load helper, models and libraries in a constructor
function __construct()
{
parent::__construct();
$this->load->helper('text');
$this->load->model('products_model'); //name of your model class
}
function index()
{
$data['products']=$this->products_model->selectAllProduct();
$this->load->view('index',$data);
}
at your view index.php
//This is an example from CI's home page
//$string = "Here is a nice text string consisting of eleven words.";
//$string = word_limiter($string, 4);
foreach($products as $p)
{
$limited_word = word_limiter($p[product_title],25);
echo $limited_word;
}
you can use my code there
<?php $artikel=$a->isi;$artikel=character_limiter($artikel,200); ?>
<p><?php echo $artikel ?></p>
Selanjutnya
<?php endforeach; ?>
First Load the helper class in either autoload.php or in the controller class.
For Global use , write in Autoload.php:
$autoload['helper'] = array('text');
OR If you want to use only in one controller.php class then:
function __construct()
{
parent::__construct();
$this->load->helper('text');
}
Then in your view.php:
<?php
if(!empty($ques)) {
foreach($ques as $list) {
$title = character_limiter($list->Title, 80); // Here we are setting the title character limit to 80
<?php echo $title;?>
}
}
?>

php - print_r() with an array of data

Working in Joomla, I have my model and view set up, but when the page is loaded, no data appears.
Model:
class mlsModelmls extends JModel
{
/**
* Gets the info
*/
function mlsdata($column)
{
$db =& JFactory::getDBO();
$query = "
SELECT *
FROM ".$db->nameQuote('#__mls')."
WHERE ".$db->nameQuote('MSTMLSNO')." = ".$db->quote('4112065').";
";
$db->setQuery($query);
$row = $db->loadRow();
print_r($row[$column]);
}
}
View:
class mlsViewmls extends JView
{
function mlsnum($tpl = null)
{
$model = &$this->getModel();
$mlsnum = $model->mlsdata(MSTMLSNO);
$this->assignRef( 'mlsnum', $mlsnum );
$agentuid = $model->mlsdata(MSTLISTBRD);
$this->assignRef( 'agentuid', $agentuid );
$listdt = $model->mlsdata(MSTLISTDT);
$this->assignRef( 'listdt', $listdt );
/** Some more assignRef() */
parent::display($tpl);
}
}
TMPL:
<h2 class="price">
<?php echo $this->mlsnum; ?>
</h2>
When the page is loaded, the TMPL looks fine, but no data appears for the <?php echo $this->mlsnum; ?> reference call.
Does each assignRef() need it's own function?
Try to change
print_r($row[$column]);
to this:
return $row[$column];
And this one
parent::display($tpl);
to
return parent::display($tpl);
Otherwise it's just no-result.
Your mlsdata() method doesn't returning anything, therefore you are assigning nothing to the template variable.
Add return $row and remove the print_r.
Try changing your model function to this:
function mlsdata($column) {
$db =& JFactory::getDBO();
$query = " SELECT * FROM ".$db->nameQuote('#__mls')." WHERE ".$db->nameQuote('MSTMLSNO')." = ".$db->quote('4112065').";
$db->setQuery($query);
$row = $db->loadRow();
return $row;
}

Categories