How to add Array to database in codeigniter? - php

I have a form with a multiselect field. I choose 3 categories for each company, but only one is added to the database.
How can I add an Array of 3 categories to my database? I use a joined table to add multiple categories to a company.
My table structure:
companies
---------
companyid
companyname
etc etc
categories
---------
categoryid
categoryname
companycategories
----------------
companycategoryid
categoryid
companyid
My controller:
function update()
{
$id = $this->uri->segment(3);
$data = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
);
if($this->input->post('logo')) { $data['logo'] = $this->input->post('logo'); }
$this->members_model->updatebedrijf($id, $data);
$b = $this->session->userdata('idbedrijven');
redirect("members/$b");
}
My model:
function updatebedrijf($id, $data)
{
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
$to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat1($to_bedrijfcategorieen2);
}
function insert_bedrijfcat1($data1)
{
echo '<pre>';
print_r($data1);
echo '</pre>';
$id = $this->uri->segment(3);
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijfcategorieen', $data1);
return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
}
My form:
<tr>
<td><?= form_label('Categorieen'); ?></td>
<td><?= form_multiselect('categorieen[]', $opties, key($selectie)); ?></td>
</tr>
The output of print_r($data1); gives me this:
Array
(
[idcategorieen] => Array
(
[0] => 11
[1] => 12
[2] => 13
)
)
Hope it is clear.

To Update one to many relation here is the technique
function insert_bedrijfcat1($data1)
{
$delete = $this->db->query("DELETE FROM `bedrijfcategorieen` WHERE `idbedrijven` = '" . $id. "'");
$id = $this->uri->segment(3);
foreach($data1['idcategorieen'] as $cat_id){
$this->db->query("INSERT INTO `bedrijfcategorieen` (`idbedrijven`,`idcategorieen` ) VALUES ('".$id."','".$cat_id."')");
}
}

Related

how to count number of present(status 1 means present) for each student and input beside each student profile under present column

daily_attendances database
below is under crud_model
public function take_attendance()
{
$students = $this->input->post('student_id');
$data['timestamp'] = strtotime($this->input->post('date'));
$data['class_id'] = html_escape($this->input->post('class_id'));
$data['section_id'] = html_escape($this->input->post('section_id'));
$data['school_id'] = $this->school_id;
$data['session_id'] = $this->active_session;
$check_data = $this->db->get_where('daily_attendances', array('timestamp' => $data['timestamp'], 'class_id' => $data['class_id'], 'section_id' => $data['section_id'], 'session_id' => $data['session_id'], 'school_id' => $data['school_id']));
if($check_data->num_rows() > 0){
foreach($students as $key => $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$attendance_id = $this->input->post('attendance_id');
$this->db->where('id', $attendance_id[$key]);
$this->db->update('daily_attendances', $data);
endforeach;
}else{
foreach($students as $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$this->db->insert('daily_attendances', $data);
endforeach;
}
$this->settings_model->last_updated_attendance_data();
$response = array(
'status' => true,
'notification' => get_phrase('attendance_updated_successfully')
);
return json_encode($response);
}
public function get_presentcount_by_student_id($student_id="",$status ="") {
$checker = array(
'student_id' => $student_id,
'status' => 1
);
$presentcount_by_student_id = $this->db->get_where('daily_attendances', $checker);
return $presentcount_by_student_id->num_rows();
}
under the list.php where it shows the student name and the number of days present for each student.The code is below but it does not count number of presents for each student.It still remains 0
<td>
<?php echo $this->crud_model->get_presentcount_by_student_id($student['user_id'],'status');?>
<br>
</td>
Student detail list shown in table format
student_detail_list
use this
$count=DB::select("SELECT COUNT(*) as num FROM 'your-table-name' where status = 1 ")->get();
and you can access this by $count[0]->num

how to display dynamic array values to view from model in codeigniter

here is my model code:
foreach ($query->result() as $row)
{
$data = array(
'ptitle' =>$row->ptitle,
'technology' => $row->technology,
'description' => $row->description,
);
$this->session->set_userdata('project',$data);
}
here is my View code:
<?php
if (isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
?>
when i print array it displays
Array ( [ptitle] => opmp [technology] => hbh [description] => kg ) Array ( [ptitle] => icicse [technology] => vv [description] => bhjv ) .can someone help me to print this values in view
Setting session should be like this
$data = array(
'ptitle' => $row['ptitle'],
'technology' => $row['technology'],
'description' => $row['description'],
);
$this->session->set_userdata($data);
To retrive them use
if (isset($this->session->userdata['project']))
{
$ptitle = $this->session->userdata('ptitle');
$technology = $this->session->userdata('technology');
$description = $this->session->userdata('description');
}
If your are storing multiple as array in SESSION then you surely need foreach in your view too.
Change from
if(isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
into
if(isset($this->session->userdata['project']))
{
foreach($this->session->userdata['project'] as $project)
{
$ptitle = $project['ptitle'];
$technology = $project['technology'];
$description = $project['description'];
echo $ptitle.'<br>'.$technology.'<br>'.$description.'<br>';
}
}
Try setting your array like bellow and then pass it to session set data.
$project = array("project" =>
array(
'ptitle' => "ptitle",
'technology' => "technology",
'description' => "description",
)
);
$this->session->set_userdata($project);

View user data along with profile pic in codeigniter?

I want to show user data along with profile pic on it's profile page i am successful in displaying the profile pic but have some doubts in my mind how can i other show user data on same page should i make other controller and model for that or single controller and model is enough to perform task.If we make another model and controller for that is it possible to or good pratice to return different data one from profile_pic controller and other from user_data controller to same view.
//My profile_pic controller
public function index() {
if($this->session->userdata('is_login')) {
$session_data = $this->session->userdata('sessiondata');
$id = $session_data['user_id'];
$this->load->model('Display_profilepicture');
$data = $this->Display_profilepicture->getImage();
//var_dump($data);
print_r($data);
//echo '<br>';
$img = base_url().'upload/thumbs/'.$data;
//echo $img.'<br>';
$data = array('img' => $img);
//print_r($data);
//$this->load->view('header');
//$this->load->view("my_profile", $data);
// $data=array('profile_picture'=>$img);
//print_r( $data['profile_picture']);
//echo '<br>';
//header("Content-type: image/jpg");
//$this->load->view('header');
//$this->load->view('my_profile',array('data'=>$data));
}
//my model
function get_user_data(){
$session_data = $this->session->userdata('sessiondata');
$id = $session_data['user_id'];
$this->db->select("*");
$this->db->from('tbl_usrs');
$this->db->where('user_id', $id);
$query = $this->db->get();
if($query->num_rows()==0)
echo("Picture not found!");
else
$data = $query->result();
return $data=$query->result();
//print_r($data['profile_picture']);
}
function getImage(){
$session_data = $this->session->userdata('sessiondata');
$id = $session_data['user_id'];
$this->db->select("*");
$this->db->from('tbl_usrs');
$this->db->where('user_id', $id);
$query = $this->db->get();
if($query->num_rows()==0)
echo("Picture not found!");
else
$data = $query->row_array();
return $data['profile_picture'];
//print_r($data['profile_picture']);
}
this is data returned from model and result of print_r($data);
Array ( [user_id] => 26 [first_name] => aman [last_name] => [username] => aman123 [sex] => [dob] => 0000-00-00 [phone] => 0 [email] => aman#gmail.com [visited_country] => 0 [about_me] => [help_others] => [fav_activity] => [bed_offer] => 0 [couch_country] => 0 [couch_state] => 0 [couch_city] => 0 [couch_addline1] => [couch_addline2] => [profile_picture] => db421e40f1c1852d8cc0acc93d7bb963.jpg [picture1] => [picture2] => [picture3] => [picture4] => [picture5] => [country] => [state] => [city] => [addline1] => [addline2] => [zip] => 0 [created_on] => 0000-00-00 [password] => 123123 [modified_on] => 0000-00-00 [active] => [user_type] => 0 [ip] => ::1 )
if make changes in my model set return $data instead of $data['profile_picture']
then array of data is returned but i get error array to string conversion due line in controller "$img = base_url().'upload/thumbs/'.$data;" so i just wana ask what is best way to perform task and how??Some code help is also accepted??
In controller
function index()
{
if ( $this->session->userdata('is_login') )
{
$session_data = $this->session->userdata('sessiondata');
$id = $session_data['user_id'];
$this->load->model('Display_profilepicture');
$result = $this->Model_name->get_user_data($id);
if($result==0)
{
echo 'No user Found';
}
else
{
$data['user']=$result;
$this->load->view('header');
$this->load->view("my_profile", $data);
}
}
}
In model
function get_user_data($id)
{
$query = $this->db->query("SELECT * FROM tbl_usrs WHERE user_id='$id'");
$result = $query->result_array();
$count = count($result);
if(empty($count) || $count > 1)
{
$log = 0;
return $log ;
}
else
{
return $result;
}
}
In View
foreach ( $user as $new_user )
{
?>
<h4>Your name: <?php echo $new_user['first_name'] ?> </h4>
<img src="<?php echo base_url()?>upload/thumbs/<?php echo $new_user['profile_picture'] ?>" alt="<?php echo $new_user['first_name'] ?>">
<p>E-Mail: <?php echo $new_user['aman#gmail.com'] ?></p>
<?php
}

CodeIgniter insert two rows instead one

I have an issue with CodeIgniter. For some reason it insert two rows in database instead one.
Below is code from model:
/**
* Add new fuel
*/
public function addNewFuel($id = NULL, $data) {
if ($id) {
var_dump('TEST');
$data = array(
'price' => '333' ,
'fuel' => 'dizelka' ,
'petrol_id' => '66'
);
echo '<pre>';
print_r($data);
echo '</pre>';
$this->db->insert('prices', $data);
echo $this->db->last_query();
$this->db->insert('prices_archive',$data);
return;
}
}
And here is output:
string(4) "TEST"
Array
(
[price] => 333
[fuel] => dizelka
[petrol_id] => 66
)
EDIT:
This is code from controller which calls model's function:
function addnewfuel() {
if ($this->session->userdata('logged_in')) {
$this->load->helper('form');
$id = $this->uri->segment(3);
$fuel = $this->input->post('fuel');
$price = $this->input->post('price');
$addNewFuel = array('fuel' => $fuel, 'price' => $price);
$data['addNewFuel'] = $this->Adminarea_model->addNewFuel($id,$addNewFuel);
$data['getFuels'] = $this->Adminarea_model->getFuels();
$data['getPetrolNameByID'] = $this->Adminarea_model->getPetrolNameByID();
$data['getPetrolInformation'] = $this->Adminarea_model->getPetrolInformation();
$this->load->view('admin/edit', $data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
For some reasons in a table 'prices' I'm getting two rows with same data, and I really don't have idea why that happens.
Thanks
You are inserting data both from controller as well as from model.
remove this from model, hope it ill solve the problem. Thanks
$data = array(
'price' => '333' ,
'fuel' => 'dizelka' ,
'petrol_id' => '66'
);

Part of the code gets skipped

I'm trying to write my own little blog.
For this, I use the CodeIgniter framework.
In my blog posts, I also want to save a category and some keywords.
I need to be able to check if a category/keyword already exists, if not a new one needs to be created.
The ID of the existing/new one is saved to be used in a 'connecting' table.
I have the following database setup.
posts - id (AI), title, date, content
categories - id (AI), category
post_categories - post, category
keywords - id (AI), keyword
post_keywords - post, keyword
*AI = Auto Increment
The tables posts, post_categories and post_keywords get updated, the tables categories and keywords remain empty. The category and keyword values in the connecting tables are ofc incorrect.
When troubleshooting my code, I echo'ed every variable in every step.
For some reason, the whole if/else structures checking whether a category or keyword already exists is skipped.
/**
* Insert post into database
* Check if category already exists, if not add it
* Check if keywords already exist, if not add them
* Insert post-category and post-keyword links
* #param array $data
* #return boolean success
*/
function create($data) {
print_r($data);
try {
// posts
$this->db->insert('posts', array(
'title' => $data['title'],
'date' => $data['date'],
'content' => $data['content']
));
$postId = $this->db->insert_id();
echo '<p>Inserted new post (' . $data['title'] . ') at ' . $postId . '</p>';
// category
$category = $data['category'];
$query = $this->db->get_where('categories', array('category' => $category));
$cat = 666;
if ($this->db->count_all_results() == 1) {
foreach ($query->result() as $row) {
$cat = $row->id;
echo '<p>cat = ' . $cat . '</p>';
}
} else {
$this->db->insert('categories', array(
'category' => $category
));
$cat = $this->db->insert_id();
echo '<p>cat = ' . $cat . '</p>';
}
echo '<p>Inserted new category (' . $category . ') at ' . $cat . '</p>';
if($cat == 666) { echo ':('; }
$this->db->insert('post_categories', array(
'post' => $postId,
'category' => $cat
));
// keywords
$keywords = $data['keywords'];
foreach ($keywords as $keyword) {
$query = $this->db->get_where('keywords', array('keyword' => $keyword));
$key = 666;
if ($this->db->count_all_results() == 1) {
foreach ($query->result() as $row) {
$key = $row->id;
echo '<p>key = ' . $key . '</p>';
}
} else {
$this->db->insert('keywords', array(
'keyword' => $keyword
));
$key = $this->db->insert_id();
echo '<p>key = ' . $key . '</p>';
}
echo '<p>Inserted new keyword (' . $keyword . ') at ' . $cat . '</p>';
if($key == 666) { echo ':('; }
$this->db->insert('post_keywords', array(
'post' => $postId,
'keyword' => $key
));
}
return true;
} catch (Exception $e) {
print '<p>ERROR:</p>' . $e;
return false;
}
}
Also in my controller
echo '<p>' . ($this->m_posts->create($post) ? 'no errors :)' : 'error! :(') . '</p>';
Result
Array ( [title] => Foo Bar [date] => 2014-05-22 [content] => lorum ipsum dolore si amet [category] => Category [keywords] => Array ( [0] => Some [1] => Keywords ) )
Inserted new post (Foo Bar) at 2
Inserted new category (Category) at 666
:(
Inserted new keyword (Some) at 666
:(
Inserted new keyword (Keywords) at 666
:(
no errors :)
In my database
POSTS
stdClass Object ( [id] => 1 [title] => Title [date] => 2014-05-22 [content] => okokokokokokok )
stdClass Object ( [id] => 2 [title] => Foo Bar [date] => 2014-05-22 [content] => lorum ipsum dolore si amet )
CATEGORIES
POST_CATEGORIES
stdClass Object ( [post] => 1 [category] => 666 )
stdClass Object ( [post] => 2 [category] => 666 )
KEYWORDS
POST_KEYWORDS
stdClass Object ( [post] => 1 [keyword] => 666 )
stdClass Object ( [post] => 2 [keyword] => 666 )
stdClass Object ( [post] => 2 [keyword] => 666 )
note: I use 99 as a temp value to test if the variable was filled because I first thought the variable's value didn't leave the scope of the if/else. But echo'ing the values of the vars inside the if/else prints nothing. It seems to skip the whole if/else sections.
Adjust the code to:
In if statement num_rows of query it self
If you expect 1 record do a $query->row() directly instead of a foreach loop.
$query = $this->db->get_where('categories', array('category' => $category));
$cat = 666;
if ($query->num_rows() == 1) {
$row = $query->row();
$cat = $row->id;
echo '<p>cat = ' . $cat . '</p>';
} else {
$this->db->insert('categories', array(
'category' => $category
));
$cat = $this->db->insert_id();
echo '<p>cat = ' . $cat . '</p>';
}

Categories