I am taking data from many tables. I want to display many objects in different places. I got the data from data base, but I want to put the data into an array for useful purpose, but it's not working.
This my controller code:
public function compare_by_business_sectors() {
//print_r($this->input->post());exit;
if ($this->input->post())
{
$solution_array = array();
//print_r (json_encode($business_sectors)); exit;
$business_sectors=$this->home_model->compare_business_sectors_data($this->input->post());
$tab_child_id = "";
$id="";
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id = array();
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
//$solution_array[$id]= $id;
}
print_r($id);
//$this->load->view('compare_by_business_sectors.php');
}
This is my model code:
public function compare_business_sectors_data($sectorid) {
$query = $this->db->select('solutions.*,solution_tabs_child_fields.field_id,solution_tabs_child_fields.tab_child_id,solution_tabs_child_fields.title')
->from('solutions')
//->join('solutions', 'business_sector.sector_id = solutions.business_sector_id',"left")
->join('solution_features','solutions.entry_id = solution_features.entry_id',"left")
->join('solution_tabs_child_fields','solution_features.field_id = solution_tabs_child_fields.field_id')
->where('solutions.business_sector_id', $sectorid['id'])
->get();
return $query->result();
//print_r($query->result());exit;
}
change it as follow and try.
$id_string = "";
$id_array = array();
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id_string = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
print_r($id_string);
print_r($id_array);
First you are assigning string value to $id then, $id will convert to array only if first if() statement execute other wise it will not be a string. So to overcome from this keep $id_array before for loop and you can capture string in another variable.
Related
I have a query that is bringing back all rows from the table instead of the fields I have specified. Can you see any mistakes in this? I'm using codeigniter.
Thanks in advance!
unset($conditions);
$conditions['conditions'] = array("accountid"=>$this->sessionInfo['database_account_id'],
"DATE_FORMAT(salestart,'%Y-%m-%d')"=>$today,
"shop"=>"london"
);
$conditions['group_by'] = "item";
$conditions['fields'] = "accountid, item, count(uniqueid) as totalitems, sum(options) as totaloptions, colour";
$today_sales = $this->Database_Model->selectData("sales",$conditions);
My model is:
public function selectData($table,$condition=array()) {
if(isset($condition['fields'])){
$fields = $condition['fields'];
}
else{
$fields = "*";
}
$this->Database->select('*');
$this->Database->from($table);
if(isset($condition['conditions'])){
$this->Database->where($condition['conditions']);
}
if(isset($condition['group_by'])){
$this->Database->group_by($condition['group_by']);
}
if(isset($condition['order_by'])){
$this->Database->order_by($condition['order_by']);
}
if(isset($condition['where_in'])){
$where_in = $condition['where_in'];
foreach($where_in as $key =>$value){
$this->Database->where_in($key,$value);
}
}
if(isset($condition['joins'])){
$joins = $condition['joins'];
foreach($joins as $join){
$this->Database->join($join['table'], $join['joinWith'],$join['type']);
}
}
$query = $this->Database->get();
return $query->result_array();
}
Change this
$this->Database->select('*');
to this
$this->Database->select($fields);
How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
In my Codeigniter project ,table value is not retrieving from database.Am using MySQL (WAMP) as database.Using Select Query i have checked the data in database and its fine there.When updating the same also its retrieving the old value in db.But when retrieving the value in later stage (ie,taking old bill) its not retrieving the value.The problem is happening only on the single field(ie,actual_price).How to solve this error.Here am attaching the screenshot and controller code for the same.
Controller Code
function bill_view($billid)
{
if(!$billid) {
redirect('report/bill_report');
}
$salecode =str_replace("_","/",$billid);
$filter ="gm_sale.saleCode ='$salecode'";
$billArray =$this->sale_model->getBillinfo($filter);
$exshowroom='';
$bank ='';
$scheme='';
$wcoNo ='';
$saleId =0;
foreach($billArray as $key=>$val) {
$exshowroom = $val['actual_price'];
$date =$val['saledate'];
$sale_to=$val['saleCustomer'];
$saleUserId=$val['saleUserId'];
$wcoNo = $val['wcoNo'];
$saleId= $val['saleId'];
if(!is_null($val['bank']) && !empty($val['bank'])){
$bank =$val['bank'];
}
if(!is_null($val['scheme_id']) && !empty($val['scheme_id'])){
$array_scheme = unserialize($val['scheme_id']);
///////////////////////////////////////////
foreach ($array_scheme as $val_scheme_id) {
$res_scheme = $this->db->get_where("gm_scheme",array('id'=>(int)$val_scheme_id));
if($res_scheme->num_rows >0){
$arrscheme = $res_scheme->row_array();
if(!empty($scheme)) {
$scheme .= ",";
}
$scheme .= $arrscheme['schemeName'];
}
}
/////////////////////////////////////////////
}
break;
}
$query = $this->db->get_where('gm_users',array('userId'=>(int)$saleUserId));
if($query->num_rows >0) {
$arrUser =$query->row_array();
}else{
$arrUser =array();
}
$data['list_product'] = $billArray;
$data['exshowroom']=$exshowroom;
$data['userinfo'] =$arrUser;
$data['saleCode'] =$salecode;
$data['sale_to'] =$sale_to;
$data['added_date'] =$date;
$data['bank'] =$bank;
$data['scheme'] =$scheme;
$data['wcoNo'] =$wcoNo;
$data['saleId'] =$saleId;
$this->load->view('header_login');
$this->load->view('report/bill_view',$data);
//print_r($billArray);
$this->load->view('footer_login');
}
Model Code
function getBillinfo($filter=''){
$this->db->select('*,gm_sale.added_date as saledate');
$this->db->from('gm_sale',FALSE);
$this->db->join('gm_products',"gm_sale.productId=gm_products.productId",FALSE);
$this->db->join('gm_model',"gm_products.model_id=gm_model.id",FALSE);
$this->db->join('gm_banks',"gm_sale.bank_id=gm_banks.bank_id","LEFT");
if($filter<>"")
$this->db->where($filter,'',FALSE);
$this->db->order_by('gm_sale.saleId',"desc");
$query = $this->db->get();
print_r($query);
if($query->num_rows>0) {
$arrRow =$query->result_array();
print_r($arrRow);
return($arrRow);
}
return(array());
}
Your code that you have in the controller doing DB stuff should be in the model.
The controller does not have context to
$this->db
modify your joins (3rd param) to retrieve values in actual_price
I am developing a CMS which works on template page system in a different approach.
I have this object:
$structure = new stdClass;
$structure->homepage->news->method = 'get_articles_by_page_name';
$structure->homepage->news->lang_key = translate('home_news');
$structure->homepage->news->lang = $lang;
$structure->homepage->news->add_media = true;
$structure->homepage->news->media_type = 'ibs';
$structure->homepage->news->limit = '5';
$structure->homepage->news->order_by = 'a.logical_date';
$structure->homepage->news->asc_des = 'desc';
$structure->homepage->news->result_type = 'result';
This helps to get contents as following:
foreach ($structure as $page_template => $page_contents)
{
// Call Customized Content for Homepage
if($this->data['page_data']->page_view == $page_template) // homepage comes ok.
{
foreach ($page_contents as $view_var_name => $page_cdata)
{
$method = $page_cdata->method; // method names comes
$page_cdata = substr(implode(",",(array) $page_cdata),(strlen($method)+1)) . '\'';
//Returns as expected:
//**'Haberler','tr','1','ibs','5','a.logical_date','desc','result'**
$this->data[$view_var_name] = $this->publish->$method($page_cdata);
vdebug($page_cdata);
}
}
}
It suppose to call them model function of:
function get_articles_by_page_name( $lang_key='',$lang='en',$add_media=true,
media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
However, there is a problem with. When I return to last worked query it says:
SELECT * FROM (`page`) JOIN `page_lang` ON `page`.`id_page` = `page_lang`.`id_page` WHERE `page_lang`.`title` = '\'News\',\'tr\',\'1\',\'ibs\',\'5\',\'a.logical_date\',\'desc\',\'result\''
It souldn't be like this. every thing between commas are parameters of the method function. What cause this, any idea?
Content of get_articles_by_page_name:
function get_articles_by_page_name ($lang_key='',$lang='tr',$add_media=true,$media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
{
// Define variables
$id_page = '';
$result = '';
// Get Page Data
$page_name = $lang_key;
$get_page = $this->vayes->getJoined('page','page_lang','id_page','','',array('page_lang.title'=>$page_name),'row');
if($get_page)
{
$id_page = $get_page->id_page;
$result = $this->publish->get_articles($lang,$id_page,null,false,'',$order_by,$asc_desc,$limit,'result');
}
else
{
$result = array('No id_page specified');
}
return $result;
}
Content of get_articles:
function get_articles($lang='tr',$id_page,$id_article=null,$incl_media=true,$media_type='',$order_by='a.logical_date',$asc_desc='desc',$limit='0',$result_type='result')
{
$this->db->select('*');
$this->db->from('article a');
$this->db->join('article_lang b','b.id_article=a.id_article','left outer');
if($incl_media) {
$this->db->join('article_media c','c.id_article=b.id_article','left outer');
$this->db->join('media d','d.id_media=c.id_media','left outer');
}
if($id_article == null) { $this->db->where('a.id_page',$id_page); }
else /*------------->*/ { $this->db->where('a.id_article',$id_article); }
$this->db->where('b.lang',$lang);
$this->db->where('b.online',1);
if(($incl_media == true) AND $media_type != '' ) $this->db->where('c.usage',$media_type);
// Order Results
$this->db->order_by($order_by,$asc_desc);
// Limit Results
if ($limit) $this->db->limit($limit);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->$result_type();
$query->free_result();
return $result;
}
return false;
}
try stripslashes()
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL. So using stripslashes() on an array you will need to do it recursively;
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);
I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.