I have an array that looks like this
Array ( [0] => test1 [1] => test4 [2] => test2 )
I got this value from my database using Codeigniter built-in function
And whenever I try to insert this value back in my database, it's inserting the index instead of the value itself
The error I'm getting is
As you can see, instead of storing test1, test4, test2 in the fields under username, it is storing the index which are 0, 1, 2.
How to fix this please?
References:
#MichaelK
TABLE:
Project Table
User Table
Project-User Table
VIEW
<div class="panel-body">
<?php echo form_open('admin/add_recommended'); ?>
<div class="form-group col-lg-12">
<label>Recommended Employees:</label>
<?php echo form_error('skillsRequired'); ?>
<?php
foreach ($users as $row) {
$user[] = $row->username;
}
print_r($user);
echo form_multiselect('user[]', $user, $user, array('class' => 'chosen-select', 'multiple style' => 'width:100%;'));
?>
</div>
</div>
<div class="panel-footer">
<?php echo form_submit(array('id' => 'success-btn', 'value' => 'Submit', 'class' => 'btn')); ?>
<?php echo form_close(); ?>
</div>
CONTROLLER
public function add_recommended() {
$this->form_validation->set_rules('skillsRequired', 'Skills Required', 'min_length[1]|max_length[55]');
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
$data['users'] = $this->admin_model->getUsers($last_id);
}
$this->load->view('admin/projects/rec-employee', $data);
if ($this->form_validation->run() === FALSE) {
//$this->load->view('admin/projects/rec-employee');
} else {
$users = $this->input->post('user');
print_r($users);
foreach ($users as $user) {
$data = array(
'projectID' => $last_id,
'username' => $user
);
$id = $this->admin_model->insert('projectemp', $data);
}
if ($id) {
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_recommended');
}
}
}
RENDERED VIEW
why you use $data['users'] in controller. Where $users contains index value. You try this
//CONTROLLER
$data = $this->admin_model->getUsers($last_id); //last id is the latest id.
//VIEW
foreach ($data as $row) {
$user[] = $row->username;
}
Boy these are too many comments for a small problem.
First of all #blakcat7, I hope you won't mind If I suggest a little change in your DB Schema. Use indexes and proper normalization it always helps. I have simulated your case on my machine.
It is your user table, I have added an ID with in this table.
Its your project table, just changed some field names, you can use your own
This is your table to create your join, Although you could have used user_id or posted_by field in projects table which could solve your problem too
Now Where i see it, you have users in your database table, you also have added projects but now you want to assign or associate that project with the user.
Make it simple just create a view where you can see both projects and users
Rendered by the Controller function
public function assignProject()
{
$data['projects']=$this->admin_model->getAll('projects');
$data['users']=$this->admin_model->getAll('user');
if($_POST)
{
$this->admin_model->assignUser($_POST);
$data['success']='User Assigned';
$this->load->view('assignProjects',$data);
}
else
{
$this->load->view('assignProjects',$data);
}
}
The view rendered by following markup
<form action="" method="post">
<div class="form-group">
<label>Project</label>
<select name="project" class="form-control">
<?php for($i=0;$i<count($projects);$i++){?>
<option value="<?php echo $projects[$i]['id']?>"><?php echo $projects[$i]['title']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Users</label>
<select name="user" class="form-control">
<?php for($i=0;$i<count($users);$i++){?>
<option value="<?php echo $users[$i]['id']?>"><?php echo $users[$i]['username']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Assing User</button>
</div>
</form>
Just hit Assign User and the following function in the Model will save it in the project-user table
public function assignUser($data)
{
$record=array(
'user_id'=>$data['user'],
'project_id'=>$data['project'],
);
$this->db->insert('user_projects',$record);
}
Remember, always use an Index (ID) field in your tables, would make your DB iteration life simpler
OKAY EVERYONE, THANKS Y'ALL FOR YOUR HELP. IT REALLY MEANS SO MUCH TO ME. AFTER LIKE 2 DAYS OF STRUGGLE I FINALLY FIXED MY PROBLEM. ^_^
Special thanks to Michael K for helping me point out the problem and Malik Mudassar for giving me the idea how to do it.
Controller
public function add_recommended() {
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
}
$data['users'] = $this->admin_model->getUsers($last_id);
$this->load->view('admin/projects/rec-employee', $data);
if ($_POST) {
$users = $this->input->post('recommended');
foreach ($users as $user):
$data = array(
'projectID' => $last_id,
'userID' => $user
);
$id = $this->admin_model->insertRecEmp($data);
endforeach;
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_project');
}
}
Model
public function getUsers($id) {
$this->db->select('*');
$this->db->from('users_skills e');
$this->db->join('projects_skills p', 'e.skillsID = p.skillsID');
$this->db->join('users u', 'u.userID = e.userID');
$this->db->where('p.projectID', $id);
$this->db->group_by('e.userID');
$this->db->order_by('e.percentage', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$result[] = $row;
}
return $result;
}
return false;
}
public function getID() {
$this->db->select_max('projectID');
$this->db->from('projects');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function insertRecEmp() {
$this->db->insert('projects_users', $data);
}
View
<form action="add_recommended" method="post">
<select name="recommended[]" class="chosen-select" multiple title='Select Skills' multiple style="width: 100%;">
<?php for ($i = 0; $i < count($users); $i++) { ?>
<option value="<?php echo $users[$i]->userID ?>"><?php echo $users[$i]->username ?></option>
<?php } ?>
</select>
</form>
I completely changed my database and my PHP function for multi select
Related
I have a script that is supposed to return values from a mysql tables based on search inputs. This script is composed of two files.
search.php
<?php
if ( isset( $_GET['s'])) {
require_once( dirname( __FILE__ ) . '/class-search.php' );
$search = new search();
$search_term = $GET['s'];
$search_results = $search->search($search_term);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<div class="search-form">
<form action="" method="get">
<div class="form-field">
<label for="search-field">Search</label>
<input type="search" name="s" placeholder="Search by name" results="5" value="<?php echo $search_term; ?>">
<input type="submit" value="Search">
</div>
</form>
</div>
<?php if ( $search_results ) : ?>
<div class="results-count">
<p><?php echo $search_results['count']; ?> results found</p>
</div>
<div class="results-table">
<?php foreach ( $search_results['results'] as $search_result ) : ?>
<div class="result">
<p><?php echo $search_result->title; ?></p>
</div>
<?php endforeach; ?>
</div>
<div class="search-raw">
<pre><?php print_r($search_results); ?></pre>
</div>
<?php endif; ?>
</body>
and class-search.php
<?php
class search {
private $mysqli;
public function __construct() {
$this->connect();
}
private function connect() {
$this->mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE' );
}
public function search($search_term) {
$sanitized = $this->mysqli->query("
SELECT * FROM `Apple`
FROM search
WHERE Last_Name LIKE '%{$sanitized}%'
");
if ( ! $query->num_rows ) {
return false;
}
while( $row = $query->fetch_object() ) {
$rows[] = $row;
}
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
}
?>
Within my database I have two tables, but I'm only interested in searching the content of one (Apple). Can somebody help me? I can't seem to make this work. No results are returned no matter what I search. As of now I'm only using the Last_Name criteria, but I'd like to add others. Here's a link to the screenshot of my table http://imgur.com/a/H3DnG.
I'd really appreciate any feedback possible. Thank you.
If you check it again,
In search method you're passing $search_term as argument but in the query you're using $sanitized which doesn't exists until the query is executed.
You're result set is in $sanitized but you're checking $query for num_rows which don't even exists. Also, you're returning false in that method so you're not able to identify the actual problem.
public function search($search_term) {
$sanitized = $this->mysqli->query("
SELECT * FROM `Apple`
FROM search
WHERE Last_Name LIKE '%{$search_term}%'
");
if ( ! $sanitized->num_rows ) {
//return false;
retrun [];
}
$rows = [];
while( $row = $sanitized->fetch_object() ) {
$rows[] = $row;
}
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
In connect method, add this which will tell whether its getting connected to database or not.
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
}
i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)
I´ve been trying this to work but seems isn´t going anywhere.
The problem is, the data doesn´t show in the View as a combobox it displays this error;
A PHP Error was encountered Severity: Notice Message: Undefined property: stdClass::$Campus Filename: views/energy_search_campus.php Line Number: 28 " >c_name.
So dunno where the problem should be... in the model, view, controller or even the db. Thanks in advance.
Model:
function campus_finder()
{
$this->db->group_by('campus');
$this->db->order_by('faculty', 'asc');
$query = $this->db->get('cpanel_energy');
if($query->num_rows()>0) {
foreach($query->result() as $row) {
$services[$row->id] = $row;
}
return $services;
}
}
View:
<div class="finder">
<div>
<label>Campus</label>
</div>
<select
id="campus"
name="campus"
class="form-control"
>
<option value="">----</option>
<?php foreach($catalogue as $item): ?>
<option value="<?php echo $item->Campus; ?>"
<?php if($campus) echo ($item->campus==$campus)? 'selected' : ''; ?>
><?php echo $item->campus; ?></option>
<?php endforeach; ?>
</select>
</div>
Controller:
function campus_search()
{
$submit = $this->input->post('send');
$campus = $this->input->post('campus');
$year = $this->input->post('year');
if($submit=='goback')
{
redirect("energy/catalogue/");
}
else
{
$data['catalogue'] = $this->model_energy_consumption->campus_finder();
$data['voucher'] = $this->model_energy_consumption->results_campus();
$data['services'] = $this->modelo_energy_consumption->services_catalogue_campus();
$data['campus'] = $campus;
$data['year'] = $year;
DB:
MAINTENANCE_JOB_ITEMS
|----|---------|---------|--------|
| id | account | faculty | campus |
|----|---------|---------|--------|
1 898946 f_name c_name
In the model you are returned $services , but the values are saved in $servicios variable
first call select function to select some record then group them
like this :
$this->db->select('user_id, first_name,last_name');
I have a database table with (NumSection (id) and NomSection)
In my page I want display all data from 'NomSection' like a link. And when I click on the link I want open my actual page with a $_POST['nomSection'] and display data of this section.
From my page index.php :
<div>
<?php
$array = returnAllSection();
foreach ($array as $section) {
// link to same page but with a $_POST['NomSection'], For the //moment I just display it.. I don't know how do with php
echo $section['NomSection'].'<br/>';
}
?>
</div>
<div>
<?php
// here I want have $array = returnAll('NomSection) or returnAll() //if empty (this function return ALL if empty or All of a section, can I just //put returnAll($_POST[nomSection]) ?
$array = returnAll();
foreach ($array as $section) {
echo 'Titre: ' .$section['TitreArticle'].'<br/>';
echo 'Date: ' .$section['DateArticle'].'<br/>';
echo 'Texte: ' .$section['TexteArticle'].'<br/>';
echo '<br/>';
}
?>
</div>
my functions: (works good)
function returnAll($arg = 'all') {
global $connexion;
if($arg == 'all'){
$query = "select
NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection or RefSection = null;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
else {
$query = "select NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection and NomSection = :arg;";
$prep = $connexion->prepare($query);
$prep->bindValue(':arg', $arg, PDO::PARAM_STR);
$prep->execute();
return $prep->fetchAll();
}
}
function returnAllSection() {
global $connexion;
$query = "select * from Sections;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
In order to post you'll need to use a form or javascript ajax post, as far as I know. Here I show a clunky form post approach that might work for what you are trying to accomplish.
<?php
function returnAllSection() {
return array(
array('NomSection' => 'foo'),
array('NomSection' => 'bar'),
array('NomSection' => 'baz'),
);
}
?>
<?php
$array = returnAllSection();
foreach ($array as $section) { ?>
<form action="" method="POST">
<button type="submit">NomSection</button>
<input type="hidden" name="NomSection" value="<?php echo htmlspecialchars($section['NomSection']); ?>">
</form>
<?php } ?>
<?php
if (isset($_POST['NomSection'])) {
error_log(print_r($_POST,1).' '.__FILE__.' '.__LINE__,0);
// do something with NomSection...
}
?>
I'm working with CodeIgniter.
I need to get some data from database with a foreach loop.
I have 4 items in the database, but the loop retrieve only two of them (the items with id 2 and 4).
This is the code in the for the foreach in the controller:
$this->load->model('home_model');
$data['query']=$this->home_model->get_films($limit);
if ($data['query']) {
$data['main_content'] = 'home';
$data['film'] = array();
foreach($data['query'] as $film_info) {
$data['film'] = array(
'id' => $film_info->id,
'poster_src' => $film_info->film_poster_src,
'title' => $film_info->film_name,
'year' => $film_info->film_year,
'genre_id' => $film_info->genre_id,
);
$this->db->select('*');
$this->db->from('genres');
$this->db->where('id', $film_info->genre_id);
$query1 = $this->db->get();
$genre_info = $query1->row();
$data['genre_name'] = $genre_info->genre_name;
$this->db->select('*');
$this->db->from('votes');
$this->db->where('film_id', $film_info->id);
$this->db->where('vote', '1');
$query2 = $this->db->get();
$data['votes_count'] = $query2->num_rows();
}
$this->load->view('template', $data);
This is the code in the model:
<?php
class Home_model extends CI_Model
{
function get_films($limit)
{
$query = $this->db->get('films', $limit, $this->uri->segment(2));
return $query->result();
}
}
And this is the code in the view:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="<?php echo $film['poster_src'] ?>" alt="Film poster">
<div class="caption">
<h3><?php echo $film['title'] ?></h3>
<p>Year: <?php echo $film['year'] ?></p>
<p>Genre: <?php echo $genre_name ?></p>
<p>Votes: <?php echo $votes_count ?></p>
<p>Watch Add to bookmarks</p>
</div>
</div>
</div>
If I put the foreach code in the view, it works properly.
I am not 100% sure so don't vote if false just make me aware i will try another way if possible.in foreach loop try to put the data in another array like this
$new_array[] = $the_result_value_you want
then you will be able to use $new_array outside the loop