Pass single OR multiple URI segments to function (code igniter) - php

Currently I have this url to view an image from the db (codeigniter) domain.com/view/id
I'd like to be able to accept multiple ids comma separated domain.com/view/id,id,id
Any idea how to go about it? Thanks
view controller part:
function view() {
$id = alphaID($this->uri->segment(1) ,true);
$this->load->model('Site_model');
if($query = $this->Site_model->get_images($id)) {
$data['records'] = $query;
}
$this->load->view('view', $data);
}
<?php if(isset($records)) : foreach($records as $row) : ?>
<?php if($row->alpha_id == $this->uri->segment(1)): ?>
<h1><?php echo $row->alpha_id.$row->file_ext; ?></h1>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>

Use this in your controller
function view() {
$id = $this->uri->segment(1);
$id_array = explode(",", $id);
$this->load->model('Site_model');
foreach ($id_array as $key => $id) {
// use alphaID function
$id = alphaID($id ,true);
if($query = $this->Site_model->get_images($id)) {
$data['records_array'][$key] = $query;
// added second array for comparison in view
$data['id_array'][$key] = $id;
}
}
$this->load->view('view', $data);
}
For your view:
<?php
foreach ($records_array as $key => $records) {
if(isset($records)) : foreach($records as $row) : ?>
// removed uri and added array
<?php if($row->alpha_id == $id_array[$key]): ?>
<h1><?php echo $row->alpha_id.$row->file_ext; ?></h1>
<?php endif; ?>
<?php endforeach; ?>
<?php endif;
}
?>

Because commas aren't valid path elements you won't be able to get this to work without having your delimited data on the right side of a ? character. You'll need to come up with another scheme or go with the comment from #jprofitt.

You are right, you can add a comma in $config['permitted_uri_chars'] but you'll have to manipulate with that segment every time you need it, unless you hook into the system core.
Haven't tested this code but you'll get an idea:
<?php
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-,'; // Note a comma...
// Controller
class Blog extends CI_Controller
{
public function posts($ids = NULL)
{
// Check if $ids is passed and contains a comma in the string
if ($ids !== NULL AND strpos($ids, ',') !== FALSE)
{
$ids = explode(',', $ids);
}
// Convert $ids to array if it has no multiple ids
is_array($ids) OR $ids = array($ids);
// $ids is an array now...
}
public function new_posts()
{
// Check if $ids is passed and contains a comma in the string
$ids = $this->uri->segment(1);
if (!empty($ids) AND strpos($ids, ',') !== FALSE)
{
$ids = explode(',', $ids);
}
// Convert $ids to array if it has no multiple ids
is_array($ids) OR $ids = array($ids);
// $ids is an array now...
}
}
?>
example.com/index.php/blog/posts/2,4,6,8
Please note once again, code may not be accurate because I haven't tested it but think it will help you.

Related

matching two columns in mysql table in codeigniter not working

i am trying to display data using 2 tables in codeigniter, i have a products table with some products and another table with the id of the products, i did the following in controller:
public function index(){
$selectfeatured = $this->product->selectfeatured();
foreach($selectfeatured as $val){
$id=$val->pid;
$data['featured'] = $this->product->featured($id);
}
$this->load->view('home', $data);
}
in my model,
function selectfeatured()
{
$this->db->select('*');
$this->db->from('featured');
$this->db->order_by("id", "desc");
$this->db->limit(4);
$query = $this->db->get();
$result = $query->result();
return $result;
}
function featured($pid)
{
$this->db->select('*');
$this->db->where("id", $pid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result();
return $result;
}
this code only displays one product even though i have multiple products in both the tables, can anyone please tell me what is wrong in here
Make your $data['feature'] as an array:
public function index()
{
$selectfeatured = $this->product->selectfeatured();
$data['featured'] = array();
foreach ($selectfeatured as $val) {
$id = $val->pid;
$data['featured'][] = $this->product->featured($id); // add new item
}
$this->load->view('home', $data);
}
And make sure you display the featured array right way in your view, something like this:
<?php foreach ($featured as $feature) : ?>
<?php foreach ($feature as $product) : ?>
<div class="item"><img style="height:250px" src="<?php echo base_url(); ?>admin/uploads/products/<?php echo $product->pimage; ?>" alt="" class="img-responsive"></div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
The variable $data['featured'] is inside a loop and is getting new value on each iteration, and is overwritten on each iteration, that's why you are getting only one product, you need to use array_push or '+=' etc to append the other products.

PHP Set array of values to the key and echo out all the values out

I'm using a simple PHP template script which has a function sets the values to the key and later replace the template tags with the key.
<?php
class Template {
protected $file;
protected $values = array();
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
public function output() {
if (!file_exists($this->file)) {
return "Error loading template file ($this->file).<br />";
}
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "[#$key]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
?>
Then I have this foreach loop, I wanted to set all of the $post_title data to post_title, then output all the values, but I only got one element of data within the foreach loop.
<?php foreach ($post_titles as $post_title): ?>
<?php $data->set("post_title", $post_title['post_title']); ?>
<?php endforeach; ?>
<?php echo $data->output(); ?>
If I edit above code in the foreach loop to <?php echo $post_title['post_title']; ?> I will get all of the elements from the variable $post_titles which is an array, however, other ways like using return or set values to post_title will only get me one element from the array.
How can I get all of the data elements within the foreach loop, not by immediately echoing out, but saved into a variable for later use outside of the foreach loop.
Edited: You have to call output function in foreach
<?php foreach ($post_titles as $post_title): ?>
<?php $data->set("post_title", $post_title['post_title']); ?>
$allData[] = $data->output();
<?php endforeach; ?>
<?php print_r($allData); ?>
Call output function in foreach with set function.
Remove square brackets from $output variable.

retrieve data from the database but the result of " array"

I tried to call up data from the model , but when running the results in view the word " array" . is there who can help me ? i am using codeigniter
Controller
$data=array('pengunjung' => $this->mcrud->jumlah_visitor(),
'isi' =>'user/monitoring');
$this->load->view('layout/wrapper', $data);
Model
function jumlah_visitor() {
$date = date("Ymd");
$this->db->where('date',$date);
$this->db->group_by(array('ip'));
$ambil= $this->db->get('tbcounter');
if ($ambil->num_rows() > 0) {
foreach ($ambil->result_array() as $data) {
$hasil[] = $data;
}
return $hasil;
}
}
View
<div class="pull-left">Hari Ini : </div>
<div class="pull-right number"> <?php echo $pengunjung; ?></div>
Result
Hari ini : array
First you check the return value of $this->mcrud->jumlah_visitor() after that you print the value. If it's an array you have to use loop for that.
<?php echo $pengunjung; ?>
to
<?php print_r($pengunjung); ?>
$pengunjung variable is array not string variable
Yes of-course...
in your Model you are returning an array
foreach ($ambil->result_array() as $data) {
$hasil[] = $data;
}
return $hasil;
The same you are trying to catch in your controller $this->mcrud->jumlah_visitor(),
return your index-key just like $data->index_key
Try printing array as pengunjung is holding an array, not a simple variable.
echo "<pre>";
print_r($this->mcrud->jumlah_visitor);
echo "</pre>";
You will get complete array info.
You can't echo an array. you should use a loop to display result of $pengunjung.
In View just use
foreach( $pengunjung as $key => $value)
{
//echo $value;
}
Rewrite your model function like this
function jumlah_visitor() {
$date = date("Ymd");
$this->db->where('date',$date);
$this->db->group_by(array('ip'));
$ambil= $this->db->get('tbcounter');
$data = $ambil->result_array();
if (data->num_rows() > 0) {
foreach ($data as $data1) {
$hasil[] = $data1;
}
return $hasil;
}
}

Extracting image value from Array in Codeigniter

I'm having issues extracting a value from an array of images via Codeigniter/MySQL. So i have a table called "image" in my database and if i echo out it i get the following code:
{"f01efdf6fe3b2bb387d3094aa701203f":{"filename":"f01efdf6fe3b2bb387d3094aa701203f.jpg","alt":"","caption":"","primary":true},"b11581adadd1848acb2898e7a284afc1":{"filename":"b11581adadd1848acb2898e7a284afc1.png","alt":"","caption":""},"2cfee6d3c334696833b1cfe13910fcf1":{"filename":"2cfee6d3c334696833b1cfe13910fcf1.png","alt":"","caption":""}}
As you can see there are 3 images there, what i need is to echo out just the image where "primary" value is:true within a foreach loop...
EDIT:
<?php
$query = $this->db->query("SELECT * FROM offers_products WHERE offer_large LIMIT 5;");
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><!-- THIS IS THE IMAGES TABLE VALUE --> <?=$row->images?> <!-- --></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
Maybe:
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
echo $primary['filename'];// should give: f01efdf6fe3b2bb387d3094aa701203f.jpg
}
To give you one last hint:
<?php
function getPrimaryImageFromJsonString($stringFromDatabase) {
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
return $primary['filename'];
}
return null;
}
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><?php echo getPrimaryImageFromJsonString($row->images);?></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
L.E: a few edits.
You have to first decode the json encoded string and extract the primary image from there:
Here is small function which you can use to extract the primary image:(You can place this function in Helper if you are using CodeIgniter)
function get_primary_image($encode_json_data)
{
$primary_image = '';
$decoded_json = json_decode($encode_json_data);
foreach($decoded_json as $obj)
{
if(isset($obj->primary) && $obj->primary == 1)
$primary_image = $obj->filename;
}
return $primary_image;
}
You can call above function in your view in following way:
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li> <?=get_primary_image($row->images)?></li><!-- Here, you call above function -->
<li><?=$row->description?></li>
<?php endforeach; ?>

How to use database object in view

I'm having trouble passing data to my view when using $query->row() I can only seem to get the value when using it in the controller.
Here's the model:
public function get_post($post_id) {
$this->db->select('id, date, title');
$this->db->from('posts');
$this->db->where('id', $post_id);
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row();
$row->title = html_purify($row->title);
$row->date_posted_iso = date('c', $row->date);
return $row;
}
The controller:
public function post($post_id) {
$row = $this->post_model->get_post($post_id);
$this->data['post'] = $row;
$this->data['meta_title'] = $row->title;
$this->template->build('post/show_post', $this->data);
}
The view:
<?php
foreach ($post as $row):
echo $row->date;
echo $row->title;
endforeach;
?>
The line $this->data['meta_title'] = $row->title; in the controller works correctly, but I don't want to explicitly define all of those variables in the controller.
I've tried with the foreach and without and get Object of class stdClass could not be converted to string
How can I correctly echo the value in my view using $query->row()?
As you are returning a row, you don't need a foreach loop, try changing your view code to:
<?php
echo $post->date;
echo $post->title;
?>
The variable should be $post and not $row as you define post element in the data array in your controller.
Try to do like this.............
public function post($post_id)
{
$row = $this->post_model->get_post($post_id);
$model = array();
$model['post'] = $row;
$this->template->build('post/show_post', $model);
}
In view fie do like this
foreach($post as $data)
{
echo $data['title'];
}

Categories