Can not run a foreach loop - php

i have a trouble with my foreach loop, it always shows warning that is: Invalid argument supplied for foreach(), can you have a look and help me solve this problem.
This is my controller:
function prod_detail($id_sp){
$this->load->model('product_model');
$data['prod_detail'] = $this->product_model->getProdDetailByProdId($id_sp);
$data['prod_errors'] = $this->product_model->getProdDataError($id_sp);
$data['error_repairing'] = $this->product_model->getProdDataErrorRepairing($id_sp);
$data['rows']= $this->membership_model->getUserData();
$data['main_content'] = 'backend/home/manproduct/prod_detail_view';
$this->load->view('includes/admin/template', $data);
}
This is my model:
function getProdDataError($id_sp){
$this->db->where('id_sp', $id_sp);
$this->db->where('status', 0);
$query = $this->db->get('loi');
if($query->num_rows()>0){
foreach ($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function getProdDataErrorRepairing($id_sp){
$this->db->where('id_sp', $id_sp);
$this->db->where('status', 1);
$query = $this->db->get('loi');
if($query->num_rows()>0){
foreach ($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
And here is my view:
if($ud->status==0){
echo 'Hoạt động';
}else if($ud->status==1){
echo '<b>Lỗi<br><ul></b>';
foreach ($prod_errors as $err) {
echo '<li>'.$err->ten_loi.'</li>';
}
echo '</ul>';
}else if($ud->status==2){
echo '<b>Đang sửa lỗi<br><ul></b>';
foreach ($error_repairing as $err) {
echo '<li>'.$err->ten_loi.'</li>';
}
echo '</ul>';
}else if($ud->status==3){
echo 'Chưa lắp đặt';
}
It's ok when $ud->status==1 but it shows a warning message when $ud->status==2. btw, i use codeigniter to develop my web, can you help?

try this (adding checks on $prod_errors/$error_repairing before trying to iterate them)
if($ud->status==0)
{
echo 'Hoạt động';
}else if($ud->status==1)
{
echo '<b>Lỗi<br><ul></b>';
// first check $prod_errors exists and is not null before iterating it
if (isset($prod_errors))
{
foreach ($prod_errors as $err)
{
echo '<li>'.$err->ten_loi.'</li>';
}
}
else{
echo "No Data found";
}
echo '</ul>';
}else if($ud->status==2)
{
echo '<b>Đang sửa lỗi<br><ul></b>';
// first check $error_repairing exists and is not null before iterating it
if (isset($error_repairing))
{
foreach ($error_repairing as $err)
{
echo '<li>'.$err->ten_loi.'</li>';
}
}
else{
echo "No Data found";
}
echo '</ul>';
}else if($ud->status==3)
{
echo 'Chưa lắp đặt';
}

Related

PHP - I have two functions that work together, but that now gives me an error, that before it wasn't there

Now they aren't working anymore, but before they were
function perm1($conn)
{
$stmt = odbc_prepare($conn, 'SELECT * FROM nivel_acesso');
$success = odbc_execute($stmt);
echo "erro 1";
echo '<ul class="perm">';
echo "erro 2";
while($myRow = odbc_fetch_array($stmt))
{
echo "erro 3";
$rows = $myRow;
echo '<li>';
echo "erro 4";
echo'<input type="checkbox" name="perm'.$rows["nivel"].'" value="'.$rows["nivel"].'"><label for="perm'.$rows["nivel"].'">'.mb_convert_encoding($rows["descricao"], 'utf8', 'latin1').'</label>';
echo '</li>';
echo "erro 5";
}
echo "erro 6";
echo '</ul>';
echo "erro 7";
if(empty($rows))
{
echo "erro 8";
return $nada = "macacos";
echo "erro 9";
}
echo "erro 10";
return $rows;
}
That's my function to show a group of checkboxes with a list of permissions from my database, the query is fine and the connection to.
function utf8_converter($array){
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
That's my function that I use to get the utf-8 of the inputs I get from the database.
When I use something like utf8_converter(perm1($conn)) it gives me this error:
Warning: array_walk_recursive() expects parameter 1 to be array, string given in [Directory of the file here + file name].php on line 35
Line 35 is:
function utf8_converter($array){
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});<--This one here
return $array;
}

read more function with codeigniter

i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more » </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"

Illegal String offset error in view codeigniter

When I try to load the data from database in views it is showing error :
A PHP ERROR WAS ENCOUNTERED
SEVERITY: WARNING
MESSAGE: ILLEGAL STRING OFFSET 'NAME'
FILENAME: CLIENT/LISTVIEW.PHP
LINE NUMBER: 7
when I var_dump the variable, its showing
STRING(1) "N"
in the result
This is in my controller file (client.php)
public function viewlistdetail()
{
$id=base64_decode($_GET['id']);
$this->load->helper('client');
$this->load->model('client/Client_model');
$this->Client_model->viewlistdetail($id);
}
This is in my model file (client_model.php)
function viewlistdetail($st)
{
//echo $st;die;
$data['page_title'] = 'List View';
$data['detail']=$this->getlistdetail($st);
$this->load->view('client/general/head',$data);
$this->load->view('client/general/header');
$this->load->view('client/listview',$data);
$this->load->view('client/general/footer');
}
public function getlistdetail($id){
// $this->db->reconnect();
try{
$query1 = $this->db->query("SELECT id,name,detail,facility,address,city FROM listing WHERE id='$id'");
$str1=array();
if ($query1->num_rows() > 0)
{
$j=0;
foreach ($query1->result() as $row1)
{
$str1=array("id"=>$row1->id,"name"=>$row1->name,"detail"=>$row1->detail,"facility"=>$row1->facility,"address"=>$row1->address);
$str1['photo']=$this->getphoto($id);
$str1['price']=$this->getprice($id);
$str1['tag']=$this->gettag($id);
$j++;
}
}
else
{
$str1="No record Found";
}
}
catch (Exception $exd){
$str1= "error";
}
return $str1;
}
View File (listview.php)
<h4><?php echo var_dump($detail['name']);?></h4>
<span class="bussadd"><?php var_dump($detail['detail']);?><span>
The following code could work here. Try it to the view page.
<h4><?php echo isset($detail['name']);?></h4>
<span class="bussadd"><?php isset($detail['detail']);?><span>
or
<h4><?php echo isset($detail['name']) ? isset($detail['name']) : ''; ?></h4>
<span class="bussadd"><?php isset($detail['detail']) ? isset($detail['detail']) : '' ;?><span>
I am not sure this is your answer. I think you will get some idea with my answer.
Change your files to
in your controller client.php
public function viewlistdetail()
{
$id=base64_decode($_GET['id']);
$this->load->helper('client');
$this->load->model('client/Client_model');
$data['page_title'] = 'List View';
$data['detail']=$this->Client_model->getlistdetail($id);
if(isset($data['detail']))
{
$this->load->view('client/general/head',$data);
$this->load->view('client/general/header');
$this->load->view('client/listview',$data);
$this->load->view('client/general/footer');
}
else
die('No list to display');
}
In Model page client_model.php
public function getlistdetail($id){
// $this->db->reconnect();
try{
$query1 = $this->db->query("SELECT id,name,detail,facility,address,city FROM listing WHERE id='$id'");
$str1=array();
if ($query1->num_rows() > 0)
{
$j=0;
foreach ($query1->result() as $row1)
{
$str1=array("id"=>$row1->id,"name"=>$row1->name,"detail"=>$row1->detail,"facility"=>$row1->facility,"address"=>$row1->address);
$str1['photo']=$this->getphoto($id);
$str1['price']=$this->getprice($id);
$str1['tag']=$this->gettag($id);
$j++;
}
}
else
{
$str1="No record Found";
}
}
catch (Exception $exd){
$str1= "error";
}
return $str1;
}
Your view file
<h4><?php var_dump($detail['name']);?></h4>
<span class="bussadd"><?php var_dump($detail['detail']);?><span>

Compare 2 csv Files in PHP with better Result

i found a very good PHP solution here for compareing 2 CSV Files.
The Only Problem is the Result Page..
index.php?f1=re1.csv&f2=re2.csv
<?php
//---- init
$strFileName1=isset($_REQUEST['f1'])?$_REQUEST['f1']:'';
$strFileName2=isset($_REQUEST['f2'])?$_REQUEST['f2']:'';
if ( !$strFileName1 ) { die("I need the first file (f1)"); }
if ( !$strFileName2 ) { die("I need the second file (f2)"); }
try {
$arrFile1 = parseData($strFileName1);
$arrFile2 = parseData($strFileName2);
} catch (Exception $e) {
die($e->getMessage());
}
$rowCount1=count($arrFile1);
$rowCount2=count($arrFile2);
$colCount1=count($arrFile1[0]);
$colCount2=count($arrFile2[0]);
$highestRowCount = $rowCount1>$rowCount2 ? $rowCount1:$rowCount2;
$highestColCount = $colCount1>$colCount2 ? $colCount1:$colCount2;
$row = 0;
$err = 0;
//---- code
echo "<h2>Vergleich $strFileName1 and $strFileName2</h2>";
echo "\n<table border=1>";
echo "\n<tr><th>Err<th>Tabelle<th>Row#<th>Col#<th>Data in $strFileName1<th>Data in $strFileName2";
while($row<$highestRowCount) {
if(!isset($arrFile1[$row])) {
echo "\n<tr><td>Row missing in $strFileName1<th>$row";
$err++;
} elseif(!isset($arrFile1[$row])) {
echo "\n<tr><td>Row missing in $strFileName2<th>$row";
$err++;
} else {
$col=0;
while($col<$highestColCount) {
if ( !isset($arrFile1[$row][$col]) ) {
echo "\n<tr><td>Data missing in $strFileName1<td>$row<td>$col<td><td>".htmlentities($arrFile2[$row][$col]);
$err++;
} elseif ( !isset($arrFile2[$row][$col]) ) {
echo "\n<tr><td>Data missing in $strFileName1<td>$row<td>$col<td>".htmlentities($arrFile1[$row][$col]) ."<td>";
$err++;
} elseif ( $arrFile1[$row][$col] != $arrFile2[$row][$col] ) {
echo "\n<tr><td>Data mismatch";
echo "<td>Tabelle <td>$row <td>$col";
echo "<td>".htmlentities($arrFile1[$row][$col]);
echo "<td>".htmlentities($arrFile2[$row][$col]);
$err++;
}
$col++;
}
}
$row++;
}
echo "</table>";
if ( !$err ) {
echo "<br/>\n<br/>\nThe two csv data files seem identical<br/>\n";
} else {
echo "<br/>\n<br/>\nThere are $err differences";
}
//---- functions
function parseData($strFilename) {
$arrParsed = array();
$handle = fopen($strFilename , "r");
if ($handle) {
while (!feof($handle)) {
$data = fgetcsv($handle , 0 , ',' , '"' );
if ( empty($data)) continue; //empty row
$arrParsed[]=$data;
}
fclose($handle);
} else {
throw new Exception("File read error at $strFilename");
}
return $arrParsed;
}
?>
The Result displays the Row# and Col# of the file..
but what i need is the Name of the Col..
This is how my CSV looks like:
ISO_COUNTRY_CODE,CNT_POSTAL_CODE,ORDER1_ADMIN_TYP_1112,ORDER2_ADMIN_TYP_1113,ORDER8_ADMIN_TYP_1119,BUILTUP_ID
AND,7,0,0,7,40
ARG,1970,25,0,514,4076
AUS,2612,9,0,10978,4597
AUT,2213,9,95,2354,10304
BEL,1148,3,11,589,3781
BGR,4507,28,0,264,5375
I want to see in which "ISO_COUNTRY_CODE" is the CNT_POSTAL_CODE wrong..
$rowname = $row; // here i want to see the RAW of the Table
"like AND or ARG etc"
$colname = $col; // here i want to see the COL of the Table
"like CNT_POSTAL_CODE
or ORDER1_ADMIN_TYP_1112 etc "

Codeigniter view shows 0 record

i've insert 5 rows into ms_kategori_material table, and made some model here
function read()
{
$query = $this->db->get('ms_kategori_material');
if($query->num_rows()>0)
{
foreach ($query->result_array() as $value) {
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
return $value;
}
else
{
return null;
}
}
and controllers
function index()
{
$data['kirim'] = $this->m_kategorimaterial->read();
echo $data; //returns KKMJ001batuKKMJ002batuKKMJ003batuKKMJ004batuKKMJ005batuArray
$this->load->view('v/vkategorimaterial',$data);
}
and the views
<?php
if ( !empty($kirim) ) {
$no = 1;
foreach ($kirim as $row) { ?>
<tr id="row">
<td id="no"><?php echo $no;?></td>
<td id="judul"><?php echo $row->Kode_Kategori_Material_Jasa;?></td>
<td id="kategori"><?php echo $row->Nama_Material_Jasa;?></td>
</tr> ?>
<?php
$no++;
}
} else { ?>
<tr id="row">
<td colspan="6" align="center">Data tidak ditemukan</td>
//the screen shows 'data tidak ditemukan' </tr>
<?php
}
?>
this is so confusing, since i can see the data in the controller, then pass them into the views, views said no data received
In your model
if($query->num_rows()>0)
{
foreach ($query->result_array() as $value) {
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
return $value;
}
it's wrong, it should be
if($query->num_rows()>0)
{
return $query->result();
}
and in your controller you should have
function index()
{
$this->load->model('m_kategorimaterial'); // load it if it's not autoloaded
$data['kirim'] = $this->m_kategorimaterial->read();
$this->load->view('v/vkategorimaterial',$data);
}
Just reread your code. You're returning $value but never populating it. See below.
{
$query = $this->db->get('ms_kategori_material');
if($query->num_rows()>0)
{
$value = $query->result(); // or result_array() but you're using it as an object in the view not an array.
return $value;
}
else
{
return null;
}
}
You are actually not returning the results in your model,
replace
foreach ($query->result_array() as $value)
{
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
with
if($query->num_rows()>0)
{
return $query->result();
}

Categories