I am learning CodeIgniter; in my program I am trying to populate a dropdown from mysql database but I seemed to be doing something wrong.
Please find below what I tried:
Model
In my model I tried to use different select methods I found online but all failed so I stick with the below method and still failed.
function getAllVendors()
{
$this->db->select('DISTINCT SUBSTRING(product_code,1,3) as vendor')
->order_by('vendor');
$q = $this->db->get('tec_sale_items');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Controller
public function allVendors(){
$this->data['vendors'] = $this->vendors_sales_model->getAllVendors();
$this->page_construct('reports/vendors_sales_details', $this->data);
}
View
<select class="form-control">
<option value="">All</option>
<?php
foreach($vendors as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
Could someone please point me to what I am doing wrong.
As I see you might be forget to call view into your controller. Load view in the controller $this->load->view("your view file name") and pass the data you got from your database.
First make sure that you are getting proper data from model. And as I see your are using current object of class $this->data['vendors'] so you have to use same in the code
<select class="form-control">
<option value="">All</option> <?php
foreach($this->data['vendors'] as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
May be it's helpful 🙂.
And you should use ci4 it's 3rd version of ci and it's no longer maintained. For better security and performance change php server 7.4 and above.
Related
why kategori_nama didn't show in fatalist.
here my controller
function index(){
$data['title']='Portal Database Buku';
$data['dropdown']=$this->m->ambildataKategori('ref_kategori');
$this->load->view('home', $data);
}
my models
function ambildataKategori(){
return $this->db->get('ref_kategori');
}
views
<input name="kategori_id">
<datalist>
<?php while($rows=mysql_fetch_assoc($dropdown)){ ?>
<option value="<?php echo $rows["kategori_nama"];?>">
<?php } ?>
</datalist>
In Codeigniter 4 the helper form_datalist(string $name, string $value, array $options) is available within the form_helper in the same way as form_dropdown().
Its worth flagging though, that the helper helpfully outputs an input type text as well - which you have no control over so may well want to edit that out of the helper!
Hope this will help you :
Note : make sure you have loaded database and model in controller or in autoload.php
Your model method ambildataKategori should be like this
public function ambildataKategori()
{
$query = $this->db->get('ref_kategori');
if ($query->num_rows() > 0 )
{
/*make sure your table has data
print_r($query->result_array());
*/
return $query->result_array();
}
}
Your view should be like this :
<?php
if ( ! empty($dropdown)){ ?>
<datalist>
<?php foreach($dropdown as $item) {?>
<option value="<?php echo $item["kategori_nama"];?>">
<?php }?>
</datalist>
<?php }?>
for reference : https://www.codeigniter.com/user_guide/general/index.html
I am serializing a form that contains one select input with an object as its value to be sent to the back-end via Ajax:
<select name="language" class="form-control">
<option value="" selected disabled>Choose a Language</option>
<option value="{ locale: 'AF', name: 'Afrikaans' }">Afrikaans</option>
...
</select>
The data is then sent via Ajax, using VueJS:
$.post("/ajax/admin/languages", $("#addLanguageForm").serialize()).done((data) => {
if (data.success) {
toastr.success("A new language has been added");
} else {
toastr.error("An error occurred");
}
})
Then, the method called by the route is triggered, and here I am checking the data by logging it:
public function store(Request $r)
{
$x = $r->input('language');
Log::info($x);
}
Will display the following:
[2018-01-29 05:52:18] local.INFO: { locale: 'AF', name: 'Afrikaans' }
I then tried to access these keys to store their values by $x->locale and $x->name, which causes the error, even being an object.
What could I be missing?
With some help and ideas, I come up with a solution. First, I modified the JSON format as #JigarShah suggested, and then, from within the Controller, following code:
public function store(Request $r)
{
$x = $r->input('language');
$d = json_decode($x);
print_r($d->name);
}
All ok.
I'm having difficulty with display data from the db to dropdown.
This is what I have tried:
form_model.php
function getEmployee()
{
$this->db->select('username');
$query = $this->db->get('tbl_usrs');
return $query->result();
}
form_controller.php
public function evaluate()
{
$data['employee'] = $this->form_model->getEmployee();
$this->load->view('evaluate_view');
}
evaluate_view.php
<select class="form-control">
<?php
foreach($employee as $row)
{
echo '<option value="'.$row->username.'">'.$row->username.'</option>';
}
?>
</select>
It's giving me an error saying I have an unidentified variable employee in my view file. I've seen problems relating to this but so far all their solutions didn't work for me.
When you load the view you have to send the data like this:
$this->load->view('evaluate_view', $data);
I have a page called index.php and inside that php i have the function of CRUD and my problem is that how can i separate the php code to html and put it in a class..please help me..
here's the php and html code i want to separate
<label class="Land_Type">
<span>Land Type</span>
<?php
include_once 'dbconfig.php';
$sql = "SELECT Land_Type_Name FROM land_type";
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0)
{
?>
<select name="Land_Type">
<option selected="selected" value="">---</option>
<?php
foreach ($results as $row)
{
?>
<option value="<?php echo $row['Land_Type_Name']; ?>"><?php echo $row['Land_Type_Name']; ?></option>
<?php
}
?>
</select>
<?php
}
?>
</label>
and here is my class
<?php
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function login($uname,$upass)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname LIMIT 1");
$stmt->execute(array(':uname'=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
Use a design pattern/architecture like MVC (Model-View-Controller) There's a lot of information to be found about this on the internet and on SO. Have a look at this question and this one for a good start.
Regarding seperating PHP from HTML: the easiest way is to use an existing template engine. Smarty is a very popular one and easy to use.
The important thing is to seperate your business logic. A class should have only one responsibility, which is called the single responsibility principle. In your example, your database class is doing 2 things: it contains the database logic (executing queries) and handling your login system. You should attempt to seperate these.
These things can be pretty confusing in the beginning. My advice is to use a MVC framework (many exist for PHP like codeigniter, cakephp,...) to understand the concepts.
I have a view (myView) in which there is a form. The form action is myController/myFunction1 which is used to validate the input variables in the form and insert it to the database by calling a model function. This works perfectly fine.
Now, I need a dropdown box inside the form, for which the values will be fetched from a table (called business) in the db.
This is the code I wrote in my model to fetch the values
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
foreach ($result->result_array() as $row) {
$new_row['value'] = htmlentities(stripslashes($row['business_name']));
$row_set[] = $new_row;
}
}
return $row_set;
}
I'm not entirely sure if this is correct.
What I need to know is, if this is correct, what should be the code inside the controller and the view to display the result as a dropdown in the form in the myView.
And if this model itself is wrong, how do I get it working?
P.S. : I'm new to CodeIgniter. I have been going through S.O and various other sites to get this thing working for quite a bit of time now. This might seem to be a repeated question for which I'm really sorry, because I could not find a solution from the already available discussions dealing with the same issue. Any help is very much appreciated.
try Model :-
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
return $result->result_array();
}
else {
return false;
}
}
Controller :-
1. include model in your controller
2. call the function and send data to view.
$this->load->model('model_name');
$this->data['dropdown'] = $this->model_name->get_dropdown_list();
$this->load->view('yourview', $this->data);
get value in view:-
print_r($dropdown)
Loop your data and make a dropdown
<select name="dropdown">
<?php foreach($dropdown as $d) {?>
<option value="<?php echo $d;?>"><?php echo $d;?></option>
<?php }?>
</select>
Call This function in controller for getting your records from DB
$data['records'] = $this->my_model->get_data();
In my_model.php
function get_data()
{
$query = "select * from my_tab";
$res = $this->db->query($query);
if ( $res->num_rows )
{
return $res->row_array();
}
return false;
}
In view.php
<select>
<?for($i=0;$i<count($records);$i++)
{
?>
<option>$records[$i]->name</option>
<?php } ?>
</select>