I am attempting to create a form where the user can insert a product into a database. One of the the things they must input is the category, which I am using a select input form to allow them to choose from the available categories (PHP and MySQL displays all the available categories). The options inside the select element is given with PHP. But for some reason, when I run the application, the categories do not show up. No errors or anything, and the connection to the database is assured. The code is below. I am using the MVC pattern, if that helps any
The file with the function (category_db.php)
<?php
function get_categories() {
global $db;
$query = "SELECT * FROM categories ORDER BY categoryID";
$statement= $db->prepare($query);
$statement->execute();
return $statement;
}
The controller for the files (index.php)
<?php
require ('../models/database.php');
require ('../models/product_db.php');
require ('../models/category_db.php');
$action = filter_input(INPUT_POST, 'action');
if($action == NULL || $action==FALSE){
$action = 'list_products';
}
if ($action == 'list_products'){
$categories = get_categories();
$category_id = filter_input(INPUT_GET, 'category_id');
if ($category_id == NULL || $category_id == FALSE){
$category_id = 1;
}
$product_item = get_product_list($category_id);
include ('product_list.php');
} else if ($action = 'delete_product') {
$product_id = filter_input(INPUT_POST, 'product_id');
$category_id = filter_input(INPUT_POST, 'category_id');
delete_product($product_id);
header("Location: .?category_id=$category_id");
}
else if($action == 'add_product'){
$categories = get_categories();
include('add_product_form.php');
}
And finally, the page that display the form (add_product_form.php)
<?php include '../includes/header.php'; ?>
<main>
<h3>Add Product Form</h3>
<form method="post" action=".">
<label for="category">Category</label>
<select name="category">
<?php foreach ( $categories as $category ) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select>
<br>
<label for="product_code">Product Code</label>
<input type="text" name="product_code"><br>
<label for="product_name">Product Name</label>
<input type="text" name="product_name"><br>
<label for="list_price">List Price</label>
<input type="text" name="list_price"><br>
<input type="submit" value="Add Product">
</form>
</main>
<?php include '../includes/footer.php'; ?>
Now I have triple checked the code, but I cannot find the problem. Any help on this would be appreciated. I am also using netbeans if that helps any
I think you should use a "fetchAll" in your function so you will return an array with all your categories :
function get_categories() {
global $db;
$query = "SELECT * FROM categories ORDER BY categoryID";
$statement= $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll(PDO::FETCH_ASSOC);
return $categories;
}
Then you can loop throught the array to get the data you want.
Related
I'm trying to give a user the ability to filter search results by ascending or descending order. It isn't working.
I think it is an issue with my select or post method or something.
What could be the reason why it isn't working?
<?php
$search = "";
if(isset($_POST["search"])){
$search = $_POST["search"];
$Ascending= $_POST["Sort By"];
$Descending= $_POST["Sort By"];
}
?>
<form method="POST">
<input type="text" name="search" placeholder="Search for Question"
value="<?php echo $search;?>"/>
<label for="Sort">SortBy:</label>
<select id="SortBy" name="Sort By">
<option value="Ascending">Ascending Order</option>
<option value="Descending">Descending Order</option>
<input type="submit"
</select>
</form>
<?php
if(isset($Ascending)) {
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/SearchTableASC.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
if(isset($Descending)){
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/DescendingOrder.sql.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
?>
<!--This part will introduce us to PHP templating,
note the structure and the ":" -->
<!-- note how we must close each check we're doing as well-->
<?php if(isset($results) && count($results) > 0):?>
<p>This shows when we have results</p>
<ul>
<!-- Here we'll loop over all our results and reuse a specific template for each iteration,
we're also using our helper function to safely return a value based on our key/column name.-->
<?php foreach($results as $row):?>
<li>
<?php echo get($row, "question")?>
Delete
</li>
<?php endforeach;?>
</ul>
<?php else:?>
<p>This shows when we don't have results</p>
<?php endif;?>
You are not using the incoming parameters correctly:
$Ascending= $_POST["Sort By"];
$Descending= $_POST["Sort By"];
Here you set ascending and descending to the same value.
You should do something like:
$ascOrDec = $_POST['Sort By'];
And than check the value of $ascOrDec before you choose your query.
I am new to codeigniter and I am working on some project and I happen to need to display a drop down but filled with data from two or more tables. I don't know if join will solve the problem. Here is my view code:
<div class="form-group">
<label class="control-label">Store Name</label>
<select class="form-control" id="store" name="store">
<?php foreach($dataget as $val)
{
?>
<option value="<?php echo $val->Store;?>"><?php echo $val->Store;?></option>
<?php
}
foreach($storename as $value)
{
?>
<option value="<?php echo $value['StoreName'];?>"><?php echo $value['StoreName'];?></option>
<?php
}
?>
</select>
</div>
and here is my model:
function get_store()
{
$this->db->select('StoreName');
$this->db->from('store');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
and here is my controller:
public function poedit()
{
$id = $this->uri->segment(3);
$data['dataget'] = $this->wip_model->getByPOId($id);
$datadrop['storename'] = $this->wip_model->get_store();
$this->load->view('header');
$this->load->view('editpo',$data);
$this->load->view('footer');
}
I am working on the edit page of the project can someone please help. Thanks in advance.
In your controller
public function poedit()
{
$id = $this->uri->segment(3);
$data['dataget'] = $this->wip_model->getByPOId($id);
$data['storename'] = $this->wip_model->get_store();
$this->load->view('header');
$this->load->view('editpo',$data);
$this->load->view('footer');
}
To stop duplicate rows you can use in your view
<div class="form-group">
<label class="control-label">Store Name</label>
<select class="form-control" id="store" name="store">
<?php
$store_name = array();
foreach($dataget as $val)
{
$store_name[] = $val->Store;
?>
<option value="<?php echo $val->Store;?>"><?php echo $val->Store;?></option>
<?php
}
foreach($storename as $value)
{
if(!in_array($value['StoreName'],$store_name))//it will stop duplication of rows...
{
?>
<option value="<?php echo $value['StoreName'];?>"><?php echo $value['StoreName'];?></option>
<?php
}
}
?>
</select>
</div>
Well, looks like you put incorrect view variable
$datadrop['storename'] = $this->wip_model->get_store();
Should be changed to
$data['storename'] = $this->wip_model->get_store();
And I'd recommend to merge 2 arrays ($dataget/$storename) into one in controller, then use one foreach in the view, the code must be better
I want to select an option of product categories from dropdown menu and show products that have that specific category.
Here is the form part from my view:
<?php $attributes = array('method'=>"POST", "class" => "myc", "id" => "myc", "name" => "dropdwn");
echo form_open_multipart('frontend/home/display', $attributes); ?>
<div class="form-group">
<div class="col-sm-9">
<select class="form-control" name="category" onchange="this.form.submit();" />
<option value="" <?php echo set_select('category', 'zero', TRUE); ?>>Categories...</option>
<option value="phone" >Phones</option>
<option value="laptops">Laptops</option>
<option value="accessories" >Accessories</option>
</select>
</div>
</div>
<?php echo form_close(); ?>
As you can see I get the option from dropdown through onchange="this.form.submit();
(if it's not a good idea please suggest other way to do, I just didn't want to use ajax, as I'm not so good at it yet, anyhow suggest what seems better).
Then in my controller I get the option and convert it to array, to use it in my model.
controller part:
public function display($sort_by='product_id', $sort_order='asc', $offset = 0)
{
$this->load->model('model_product');
$selected = implode(" ", $this->input->post());
//var_dump($selected);
$results = $this->model_product->fetch($selected, $limit, $offset, $sort_by, $sort_order);
$data['products'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//and then goes pagination part, I guess no meaning posting it, as it works fine.
}
My model:
function fetch($selected, $limit, $offset, $sort_by, $sort_order)
{
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('product_id', 'name', 'description', 'category', 'country', 'price');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'product_id';
//actual results query
$q = $this->db->select('product_id, name, description, category, country, price, img_name, thumb_name')
->from('products')
->where('category', $selected)
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
var_dump($ret['rows']);
die;
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('products');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
Here I get no results, probobly because where clause returns no result.
However if I change the where clause such as ->where('category', 'phones') it shows only phones. So how can I pass selected value to the query correctly?
i wil help you.
View file
<div class="box-header">
<h3 class="box-title">Enter Category Details</h3>
</div>
<?php
echo validation_errors(); $attributes = array('id' => 'formCategory','name'=>'formCategory');
?>
<?php echo form_open_multipart(base_url().'moderator/B2BCategory/addcategory'); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="txtcatname">Title of Category :</label>
<input type="text" name="txtcatname" class="form-control" id="txtcatname" placeholder="Category Name " required="required">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="categorysection">Section of the Category :</label>
<select class="form-control" name="categorysection" required>
<option value="" >----Select------</option>
<option value="1">Laptop</option>
<option value="2">Phone</option>
<option value="3">Accessories</option>
</select>
<input type="submit" name="selsub" class="btn btn-primary">
</div>
</div>
</div>
Controller
public function addcategory() {
$this->load->helper(array('form', 'url'));
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
if ($this->input->post('selsub')) {
$data = array('ctg_name' => $this->input->post('categorysection'));
$this->b2bcategory_model->form_insert($data);
}
In Model
public function form_insert($data){
$this->db->insert('jil_category', $data);
}
To display output from table,just use
public function viewall()
{
$this->db -> select('*');
$this -> db -> from('jil_category');
$query = $this -> db -> get();
return $query->result();
}
From
$selected = implode(" ", $this->input->post());
To
$selected = $this->input->post('category');
By the way, echo & var_dump() would be very useful in debugging your controller and/or model.
im still learning codeigniter and have come up with a problem. That is
You must use the "set" method to update an entry.
I am trying to update a table : product which contains product_name, product_desc etc columns below are my controller ,view and model .. i cannot figure out what am i doing wrong .. I always checked out print_r($array); it gives me an empty array ... although i do get product details displayed in the input fields on the link : ci/index.php/admin/product/1 ..
posting half code for view as the view code is long ..
Controller :
//**** For editing product ****//
public function edit_products(){
$data = array ('product_name'=>$this->input->post('product_name'),
'product_desc'=>$this->input->post('product_desc'),
'product_stock'=>$this->input->post('product_stock'),
'product_sku'=>$this->input->post('product_sku'),
'inventory_date'=>$this->input->post('inventory_date'),
'product_price'=>$this->input->post('product_price'),
'featured_product'=>$this->input->post('featured_product'),
'best_seller'=>$this->input->post('best_seller'),
'brand_id'=>$this->input->post('brand_id'),
);
$upd_pr = $this->mainmodel->update_product($_POST);
if($upd_pr){
$this->session->set_flashdata('messages', 'Updated Sucessfully');
redirect('admin/editing_products');
}else{
$this->session->set_flashdata('error', 'Updation Failed');
redirect('admin/editing_products');
}
}
public function editing_products(){
$data['product']=$this->mainmodel->set_pro2();
//$data['images'] = $this->products->images($id);
$data['content']='admin/edit_products';
$this->load->view('admin/main',$data);
}
Model :
/*for update Product*/
public function update_product($array){
extract($array);
//print_r($array);
//die;
$this->db->update('product',array('product_name'=>$product_name,'product_desc'=>$product_desc,'inventory_date'=>$inventory_date,'product_price'=>$product_price,'featured_product'=>$featured_product,'best_seller'=>$best_seller,'brand_id'=>$brand_id));
$this->db->update('product');
return ;
}
function set_pro2(){
$q = $this->db->query('SELECT * FROM product,product_image,category_product WHERE product.product_id = category_product.product_id AND product.product_id = 1 LIMIT 1');
if($q->num_rows() > 0){
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
}
}
View :
<form class="form-horizontal form-row-seperated" enctype="multipart/form-data" action="<?php echo site_url('admin/edit_products') ?>" method="post">
<div class="form-group">
<?php foreach($product as $pro){ ?>
<label class="col-md-2 control-label">Name:<span class="required">
* </span>
</label>
<div class="col-md-10">
<input type="text" class="form-control" name="product_name" placeholder="" value="<?php echo $pro->product_name; ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Description: <span class="required">
* </span>
</label>
<div class="col-md-10">
<input type="text" class="form-control" name="product_desc" value="<?php echo $pro->product_desc; ?>">
</div>
</div>
In some cases codeigniter updates / inserts require this->db->set if in array. I also would not recommend placing two db->update to the same table as you have added on model.
Active record guide http://www.codeigniter.com/user_guide/database/active_record.html
Update
// $brand_id = 0, $data are from the edit function on controller
public function name($brand_id = 0, $data) {
$product_name = $this-input->post('product_name');
$product_desc = $this-input->post('product_desc');
$inventory_date = $this-input->post('inventory_date');
$product_price = $this-input->post('product_price');
$featured_product = $this-input->post('featured_product');
$best_seller = $this-input->post('best_seller');
$data = array(
'product_name'=> $product_name,
'product_desc'=> $product_desc,
'inventory_date'=>$inventory_date,
'product_price'=>$product_price,
'featured_product'=> $featured_product,
'best_seller'=> $best_seller,
'brand_id'=> $this->uri->segment(what_ever)
);
$this->db->set($data);
$this->db->update('product');
}
Or insert
$data = array(
'product_name'=> $product_name,
'product_desc'=> $product_desc,
'inventory_date'=>$inventory_date,
'product_price'=>$product_price,
'featured_product'=> $featured_product,
'best_seller'=> $best_seller,
'brand_id'=>$brand_id
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert('product');
Post Update
Set routes $route['function/edit/(:any)'] = 'folder/products_list/edit/$1';
If need to update a product you need to set a function called edit on the
Model Get
public function model_get_products() {
return $this->db->get($this->db->dbprefix . 'products')->result_array();
}
Controller for uri segment help http://www.codeigniter.com/user_guide/libraries/uri.html
public function edit() {
Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('what ever');
if ($this->form->validation->run() == TRUE) {
$this->load->model('folder/model_update_product');
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
$this->model_update_product->name($this->uri->segment('what_ever_is'), $this->input->post())
redirect('function/product_list');
} else {
// Load Your Form View i.e. $this->get_form();
}
}
public function index() {
$this->load->model('folder/model_get_products');
$results = $this->model_get_products->get();
$data['products'] = array();
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
// Add What Else You Need to here and then you can add it to view
foreach($results as $result) {
$data['products'][] = array(
'brand_id' => $result[brand_id],
'edit' => site_url('controller_name/edit'). '/' .$result[brand_id] // site_url must match what you set in routes for edit.
);
}
return $this->load->view('folder/products_list', $data);
}
public function get_form() {
//Example uri segment admin/product_list/edit/id_number $this->uri->segment('4')
// Make sure you set another model function in your get model where can get by id.
$product_info = $this->get_products_by_id->get($this->uri->segment('4'));
$product_name = $this->input->post('product_name');
if (isset($product_name)) {
$data['product_name'] = $product_name; // for name="" in input
} elseif (!empty($product_info)) {
$data['product_name'] = $product_info['product_name']; // for value="" in input
} else {
$data['product_name'] = '';
}
$this->load->view('folder/product_form', $data);
product form contents
}
view product list
<form>
<table>
<thead>
</thead>
<tbody>
<?php if ($products) { ?>
<?php foreach ($products as $product) { ?>
<tr>
<td><?php echo $product['brand_id'];?></td>
<td> Edit Product</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</form>
I have list of record in my index page. Now i want to search a particular record/records by choosing the category (e.g phone No, email etc).How can i do this? help..
Here is my view:
<?php
$attributes = array('class'=>'searchform', 'id'=>'searchform');
echo form_open('crud/searchCrud', $attributes);?>
<div class="formelements">
<div class="formlbl">
Search:
</div>
<div class="forminput">
<input type="text" name="searchon" id ="searchon"/>
</div>
<div class="searchtyp">
<select class="searchby" name="searchby">
<option value="0">---Select--- </option>
<option value="name">Name</option>
<option value="email">Email</option>
<option value="phone">Phone</option>
</select>
</div>
<div class="searchinput">
<input type="submit" name="search" value="Search" />
</div>
</div>
<?php echo form_close();?>
Here is My controller:
public function searchCrud()
{
$records = $this->crud_mdl->searchCrud();
foreach ($records as $record) {
echo $record->name;
}
}
Here is My Model:
public function searchCrud()
{
$searchby = $this->input->post('searchby');
$searchon = $this->input->post('searchon');
$this->db->get('test')->result();
return $this->db->like($searchon, $searchby);
}
1) You should never access POST data directly in the Model.
2) Always collect them in Controller and then pass it to the Model.
3) Also always try to create your Model functions, re-usable.
Modified your code a bit. Try running it.
Controller:
public function searchCrud()
{
$searchby = $this->input->post('searchby');
$searchon = $this->input->post('searchon');
$records = $this->crud_mdl->searchCrud($searchby, $searchon);
foreach ($records as $record)
{
echo $record->name;
}
}
Model:
public function searchCrud($searchby, $searchon)
{
$this->db->like($searchon, $searchby);
$query = $this->db->get('test');
if($query->num_rows() > 0)
return $query->result();
else
return FALSE;
}