Codeigniter Database Update Issue - php

I want to update my data but the column mark_obtained does not update. I don't know why, do I have something wrong in my code?
This is in my controller code :
function marks($exam_id = '', $class_id = '', $subject_exam_id = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($this->input->post('operation') == 'selection') {
$page_data['exam_id'] = $this->input->post('exam_id');
$page_data['class_id'] = $this->input->post('class_id');
$page_data['subject_exam_id'] = $this->input->post('subject_exam_id');
if ($page_data['exam_id'] > 0 && $page_data['class_id'] > 0 && $page_data['subject_exam_id'] > 0) {
redirect(base_url() . 'index.php?admin/marks/' . $page_data['exam_id'] . '/' . $page_data['class_id'] . '/' . $page_data['subject_exam_id'], 'refresh');
} else {
$this->session->set_flashdata('mark_message', 'Choose exam, class and subject');
redirect(base_url() . 'index.php?admin/marks/', 'refresh');
}
}
if ($this->input->post('operation') == 'update') {
$students = $this->db->get_where('enroll' , array('class_id' => $class_id , 'year' => $running_year))->result_array();
foreach($students as $row) {
$data['mark_obtained'] = $this->input->post('mark_obtained_' . $row['student_id']);
$data['comment'] = $this->input->post('comment_' . $row['student_id']);
$this->db->where('mark_id', $this->input->post('mark_id_' . $row['student_id']));
$this->db->update('mark', array('mark_obtained' => $data['mark_obtained'] , 'comment' => $data['comment']));
}
$this->session->set_flashdata('flash_message' , get_phrase('data_updated'));
redirect(base_url() . 'index.php?admin/marks/' . $this->input->post('exam_id') . '/' . $this->input->post('class_id') . '/' . $this->input->post('subject_exam_id'), 'refresh');
}
$page_data['exam_id'] = $exam_id;
$page_data['class_id'] = $class_id;
$page_data['subject_exam_id'] = $subject_exam_id;
$page_data['page_info'] = 'Exam marks';
$page_data['page_name'] = 'marks';
$page_data['page_title'] = get_phrase('manage_exam_marks');
$this->load->view('backend/index', $page_data);
}
and this is my view :
<?php if($exam_id >0 && $class_id >0 && $subject_exam_id >0 ):?>
<?php
////CREATE THE MARK ENTRY ONLY IF NOT EXISTS////
$students = $this->db->get_where('enroll' , array(
'year' => $running_year , 'class_id' => $class_id
))->result_array();
foreach($students as $row):
$verify_data = array( 'exam_id' => $exam_id ,
'class_id' => $class_id ,
'subject_exam_id' => $subject_exam_id ,
'year' => $running_year,
'student_id' => $row['student_id']);
$query = $this->db->get_where('mark' , $verify_data);
if($query->num_rows() < 1)
$this->db->insert('mark' , $verify_data);
endforeach;
<input type="number" value="<?php echo $row2['mark_obtained'];?>" name="mark_obtained" class="form-control" >
Please help me solve the issue.

if ($this->input->post('operation') == 'update') {
$data['mark_obtained'] = $this->input->post('mark_obtained');
$data['comment'] = $this->input->post('comment');
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark_obtained', $data); // ***MAYBE THIS WAS THE ISSUE****
$this->session->set_flashdata('flash_message' , get_phrase('data_updated'));
redirect(base_url() . 'index.php?admin/marks/' . $this->input->post('exam_id') . '/' . $this->input->post('class_id') . '/' . $this->input->post('subject_id'), 'refresh');
}
I pointed out to a line I corrected, which may have been the issue. You say the mark_obtained column was not beeing updated but you were actaully updating a column called mark in your code.

Related

Duplicating scores after two or more attempts in online exam

I have a school web app that has an online exam feature## Heading ##Students are given a number of times they can attempt the exam.
However, when a student attempts the exam two or more times and saves, the scores are duplicated in the database instead of being updated.
I will like that when a student attempts an exam again, the previous scores are overwritten or replaced not duplicated.
Controller:
public function save()
{
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$total_rows = $this->input->post('total_rows');
if (!empty($total_rows)) {
$save_result = array();
foreach ($total_rows as $row_key => $row_value) {
if (($_POST['question_type_' . $row_value]) == "singlechoice") {
if (isset($_POST['radio' . $row_value])) {
$save_result[] = array(
'onlineexam_student_id' => $this->input->post('onlineexam_student_id'),
'onlineexam_question_id' => $this->input->post('question_id_' . $row_value),
'select_option' => $_POST['radio' . $row_value],
'attachment_name' => "",
'attachment_upload_name' => "",
);
}
} elseif (($_POST['question_type_' . $row_value]) == "true_false") {
# code...
if (isset($_POST['radio' . $row_value])) {
$save_result[] = array(
'onlineexam_student_id' => $this->input->post('onlineexam_student_id'),
'onlineexam_question_id' => $this->input->post('question_id_' . $row_value),
'select_option' => $_POST['radio' . $row_value],
'attachment_name' => "",
'attachment_upload_name' => "",
);
}
} elseif (($_POST['question_type_' . $row_value]) == "multichoice") {
# code...
if (isset($_POST['checkbox' . $row_value])) {
$save_result[] = array(
'onlineexam_student_id' => $this->input->post('onlineexam_student_id'),
'onlineexam_question_id' => $this->input->post('question_id_' . $row_value),
'select_option' => json_encode($_POST['checkbox' . $row_value]),
'attachment_name' => "",
'attachment_upload_name' => "",
);
}
} elseif (($_POST['question_type_' . $row_value]) == "descriptive") {
# code...
if (isset($_POST['answer' . $row_value]) || (isset($_FILES["attachment" . $row_value]) && !empty($_FILES["attachment" . $row_value]['name']))) {
$inst_array = array(
'onlineexam_student_id' => $this->input->post('onlineexam_student_id'),
'onlineexam_question_id' => $this->input->post('question_id_' . $row_value),
'select_option' => $_POST['answer' . $row_value],
);
$file_name = "";
$upload_file_name = "";
if (isset($_FILES["attachment" . $row_value]) && !empty($_FILES["attachment" . $row_value]['name'])) {
$file_name = $_FILES["attachment" . $row_value]["name"];
$fileInfo = pathinfo($_FILES["attachment" . $row_value]["name"]);
$upload_file_name = time() . uniqid(rand()) . '.' . $fileInfo['extension'];
move_uploaded_file($_FILES["attachment" . $row_value]["tmp_name"], "./uploads/onlinexam_images/" . $upload_file_name);
}
$inst_array['attachment_name'] = $file_name;
$inst_array['attachment_upload_name'] = $upload_file_name;
$save_result[] = $inst_array;
}
}
}
$this->onlineexamresult_model->add($save_result);
$this->onlineexam_model->updateExamResult($this->input->post('onlineexam_student_id'));
redirect('user/onlineexam', 'refresh');
}
} else {
}
}
model:
public function add($data_insert)
{
$this->db->trans_begin();
if (!empty($data_insert)) {
$this->db->insert_batch('onlineexam_student_results', $data_insert);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}

Pragmatically disable payment method if not in specific zone opencart

How would i disable 'Cash On Delivery' payment method in opencart 2.x checkout if the selected address is from a zone_id that i don't want
I don't know the specific variable to do the logic; I have tried adding the logic below but it does not work
if (($this->config->get('cod_geo_zone_id')) == 1736) {
$status = true;
} else {
$status = false;
}
The complete code is as below in: catalog\model\payment\cod.php
<?php
class ModelPaymentCOD extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/cod');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cod_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('cod_total') > 0 && $this->config->get('cod_total') > $total) {
$status = false;
} elseif (!$this->config->get('cod_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
}
else {
$status = false;
}
if (($this->config->get('cod_geo_zone_id')) == 1736) {
$status = true;
} else {
$status = false;
}
/*$zonex = $address['zone_id'];
if ($zonex == 1736) {
$status = false;
}*/
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'cod',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('cod_sort_order')
);
}
return $method_data;
}
}
Any help will be appreciated

Add text shipping value in Opencart

We provide emailed quotes after an order is recieved in OpenCart. How can I add a field to show TBC instead of £0.00 in OpenCart. We use X-Shipping for our 4 delivery options:
Is this possible?
Here is the PHP code for the catalog side
<?php
class ModelShippingXshipping extends Model {
function getQuote($address) {
$this->load->language('shipping/xshipping');
$method_data = array();
$quote_data = array();
for($i=1;$i<=12;$i++)
{
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('xshipping_geo_zone_id'.$i) . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if (!$this->config->get('xshipping_geo_zone_id'.$i)) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
if (!$this->config->get('xshipping_status'.$i)) {
$status = false;
}
if (!$this->config->get('xshipping_name'.$i)) {
$status = false;
}
$shipping_cost=$this->config->get('xshipping_cost'.$i);
$free_shipping_cost=(float)$this->config->get('xshipping_free'.$i);
if(empty($free_shipping_cost))$free_shipping_cost=0;
if ($this->cart->getSubTotal() >= $free_shipping_cost && $free_shipping_cost!=0) {
$shipping_cost = 0;
}
if ($status) {
$quote_data['xshipping'.$i] = array(
'code' => 'xshipping'.'.xshipping'.$i,
'title' => $this->config->get('xshipping_name'.$i),
'cost' => $shipping_cost,
'tax_class_id' => $this->config->get('xshipping_tax_class_id'.$i),
'text' => $this->currency->format($this->tax->calculate($shipping_cost, $this->config->get('xshipping_tax_class_id'.$i), $this->config->get('config_tax')))
);
}
}
if(!$quote_data) return array();
$method_data = array(
'code' => 'xshipping',
'title' => $this->language->get('text_title'),
'quote' => $quote_data,
'sort_order' => $this->config->get('xshipping_sort_order'),
'error' => ''
);
return $method_data;
}
}
?>

Opencart pavblog latest module - take the latest from specific category

How can I modify the module so it takes only the articles from a specific category (ID = 35) of the articles?
The below code takes all the articles for the opencart module pavblog. I would like to change it so it does take only articles with category id of 35.
Please let me know how is it possible to change this code.
It was taken from catalog/controller/module folders in opencart.
<?php
class Controllermodulepavbloglatest extends Controller {
protected function index($setting) {
static $module = 0;
$this->load->model('pavblog/blog');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$this->language->load('module/pavblog');
$this->data['button_cart'] = $this->language->get('button_cart');
if( !defined("_PAVBLOG_MEDIA_") ){
if (file_exists('catalog/view/theme/' . $this->config->get('config_template') . '/stylesheet/pavblog.css')) {
$this->document->addStyle('catalog/view/theme/' . $this->config->get('config_template') . '/stylesheet/pavblog.css');
} else {
$this->document->addStyle('catalog/view/theme/default/stylesheet/pavblog.css');
}
define("_PAVBLOG_MEDIA_",true);
}
$default = array(
'latest' => 1,
'limit' => 9
);
$this->data['width'] = $setting['width'];
$this->data['height'] = $setting['height'];
$this->data['cols'] = (int)$setting['cols'];
$this->data['tabs'] = array();
$data = array(
'sort' => 'b.`created`',
'order' => 'DESC',
'start' => 0,
'limit' => $setting['limit']
);
if( $setting['tabs'] == 'featured' ){
$data['featured'] = 1;
$blogs = $this->model_pavblog_blog->getListBlogs( $data );
$this->data['heading_title'] = $this->language->get('text_featured');
}elseif( $setting['tabs'] == 'mostviewed' ){
$data['sort'] = 'b.`hits`';
$blogs = $this->model_pavblog_blog->getListBlogs( $data );
$this->data['heading_title'] = $this->language->get('text_mostviewed');
}else {
$blogs = $this->model_pavblog_blog->getListBlogs( $data );
$this->data['heading_title'] = $this->language->get('text_latest');
}
$this->load->model('pavblog/category');
$users = $this->model_pavblog_category->getUsers();
foreach( $blogs as $key => $blog ){
if( $blogs[$key]['image'] ){
$blogs[$key]['thumb'] = $this->model_tool_image->resize($blog['image'], $setting['width'], $setting['height'] );
}else {
$blogs[$key]['thumb'] = '';
}
$blogs[$key]['description'] = html_entity_decode($blog['description'], ENT_QUOTES, 'UTF-8');
$blogs[$key]['author'] = isset($users[$blog['user_id']])?$users[$blog['user_id']]:$this->language->get('text_none_author');
$blogs[$key]['category_link'] = $this->url->link( 'pavblog/category', "path=".$blog['category_id'] );
$blogs[$key]['comment_count'] = 10;
$blogs[$key]['link'] = $this->url->link( 'pavblog/blog','id='.$blog['blog_id'] );
}
if( isset( $setting['description'][$this->config->get('config_language_id')] ) ) {
$this->data['message'] = html_entity_decode($setting['description'][$this->config->get('config_language_id')], ENT_QUOTES, 'UTF-8');
}else {
$this->data['message'] = '';
}
$this->data['blogs'] = $blogs;
$this->data['module'] = $module++;
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/pavbloglatest.tpl')) {
$this->template = $this->config->get('config_template') . '/template/module/pavbloglatest.tpl';
} else {
$this->template = 'default/template/module/pavbloglatest.tpl';
}
$this->render();
}
}
?>
The code you are referring to
<?php
/******************************************************
* #package Pav blog module for Opencart 1.5.x
* #version 1.0
* #author http://www.pavothemes.com
* #copyright Copyright (C) Feb 2013 PavoThemes.com <#emai:pavothemes#gmail.com>.All rights reserved.
* #license GNU General Public License version 2
*******************************************************/
/**
* class ModelPavblogBlog
*/
class ModelPavblogBlog extends Model {
public function __construct( $registry ){
parent::__construct( $registry );
$this->isInstalled();
}
/**
* Get Blog Information by Id
*/
public function getInfo( $id ){
$query = ' SELECT b.*,bd.title,bd.description,cd.title as category_title,bd.content FROM '
. DB_PREFIX . "pavblog_blog b LEFT JOIN "
. DB_PREFIX . "pavblog_blog_description bd ON b.blog_id=bd.blog_id LEFT JOIN "
. DB_PREFIX . 'pavblog_category c ON c.category_id=b.category_id LEFT JOIN '
. DB_PREFIX . 'pavblog_category_description cd ON (c.category_id=cd.category_id AND cd.language_id='.(int)$this->config->get('config_language_id').')' ;
$query .=" WHERE bd.language_id=".(int)$this->config->get('config_language_id');
$query .= " AND b.blog_id=".(int)$id;
$query = $this->db->query( $query );
$blog = $query->row;
return $blog;
}
/**
* update hit time after read
*/
public function updateHits( $id ){
$sql = ' UPDATE '.DB_PREFIX.'pavblog_blog SET hits=hits+1 WHERE blog_id='.(int)$id;
$this->db->query( $sql );
}
/**
* get list of blogs in same category of current
*/
public function getSameCategory( $category_id, $blog_id, $limit=10 ){
$data = array(
'filter_category_id' => $category_id,
'not_in' => $blog_id,
'sort' => 'created',
'order' => 'DESC',
'start' => 0,
'limit' => $limit
);
return $this->getListBlogs( $data );
}
/**
* get total blog
*/
public function getTotal( $data ){
$sql = ' SELECT count(b.blog_id) as total FROM '
. DB_PREFIX . "pavblog_blog b LEFT JOIN "
. DB_PREFIX . "pavblog_blog_description bd ON b.blog_id=bd.blog_id and bd.language_id=".(int)$this->config->get('config_language_id')." LEFT JOIN "
. DB_PREFIX . 'pavblog_category c ON c.category_id=b.category_id LEFT JOIN '
. DB_PREFIX . 'pavblog_category_description cd ON c.category_id=cd.category_id and cd.language_id='.(int)$this->config->get('config_language_id') ;
$sql .=" WHERE bd.language_id=".(int)$this->config->get('config_language_id');
if( isset($data['filter_category_id']) && $data['filter_category_id'] ){
$sql .= " AND b.category_id=".(int)$data['filter_category_id'];
}
if( isset($data['filter_tag']) && $data['filter_tag'] ){
$tmp = explode (",",$data['filter_tag'] );
if( count($tmp) > 1 ){
$t = array();
foreach( $tmp as $tag ){
$t[] = 'b.tags LIKE "%'.$this->db->escape( $tag ).'%"';
}
$sql .= ' AND '.implode(" OR ", $t ).' ';
}else {
$sql .= ' AND b.tags LIKE "%'.$this->db->escape( $data['filter_tag'] ).'%"';
}
}
$query = $this->db->query( $sql );
return $query->row['total'];
}
/**
* get list blogs
*/
public function getListBlogs( $data ){
$sql = ' SELECT b.*,bd.title,bd.description,cd.title as category_title FROM '
. DB_PREFIX . "pavblog_blog b LEFT JOIN "
. DB_PREFIX . "pavblog_blog_description bd ON b.blog_id=bd.blog_id and bd.language_id=".(int)$this->config->get('config_language_id')." LEFT JOIN "
. DB_PREFIX . 'pavblog_category c ON c.category_id=b.category_id LEFT JOIN '
. DB_PREFIX . 'pavblog_category_description cd ON c.category_id=cd.category_id and cd.language_id='.(int)$this->config->get('config_language_id') ;
$sql .=" WHERE b.status = '1' AND bd.language_id=".(int)$this->config->get('config_language_id');
if( isset($data['filter_category_id']) && $data['filter_category_id'] ){
$sql .= " AND b.category_id=".(int)$data['filter_category_id'];
}
if( isset($data['filter_tag']) && $data['filter_tag'] ){
$tmp = explode (",",$data['filter_tag'] );
if( count($tmp) > 1 ){
$t = array();
foreach( $tmp as $tag ){
$t[] = 'b.tags LIKE "%'.$this->db->escape( $tag ).'%"';
}
$sql .= ' AND '.implode(" OR ", $t ).' ';
}else {
$sql .= ' AND b.tags LIKE "%'.$this->db->escape( $data['filter_tag'] ).'%"';
}
}
if( isset($data['featured']) ){
$sql .= ' AND featured=1 ';
}
if( isset($data['not_in']) && $data['not_in'] ){
$sql .= ' AND b.blog_id NOT IN('.$data['not_in'].')';
}
$sort_data = array(
'bd.title',
'b.hits',
'b.`position`',
'b.`created`',
'b.created'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
}else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY b.`position`";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC, LCASE(bd.title) DESC";
} else {
$sql .= " ASC, LCASE(bd.title) ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query( $sql );
$blogs = $query->rows;
return $blogs;
}
public function isInstalled() {
$sql = " SHOW TABLES LIKE '".DB_PREFIX."pavblog_blog'";
$query = $this->db->query( $sql );
if( count($query->rows) <=0 ){
$file = dirname(DIR_APPLICATION).'/admin/model/sample/module.php';
if( file_exists($file) ){
require_once( $file );
$sample = new ModelSampleModule( $this->registry );
$result = $sample->installSampleQuery( $this->config->get('config_template'),'pavblog', true );
}
return false;
}
return true;
}
public function getDefaultConfig(){
return array(
'children_columns' => '3',
'general_cwidth' => '250',
'general_cheight' => '250',
'general_lwidth'=> '620',
'general_lheight'=> '300',
'general_sheight'=> '250',
'general_swidth'=> '250',
'general_xwidth' => '80',
'general_xheight' => '80',
'cat_show_hits' => '1',
'cat_limit_leading_blog'=> '1',
'cat_limit_secondary_blog'=> '5',
'cat_leading_image_type'=> 'l',
'cat_secondary_image_type'=> 's',
'cat_show_title'=> '1',
'cat_show_image'=> '1',
'cat_show_author'=> '1',
'cat_show_category'=> '1',
'cat_show_created'=> '1',
'cat_show_readmore' => 1,
'cat_show_description' => '1',
'cat_show_comment_counter'=> '1',
'blog_image_type'=> 'l',
'blog_show_title'=> '1',
'blog_show_image'=> '1',
'blog_show_author'=> '1',
'blog_show_category'=> '1',
'blog_show_created'=> '1',
'blog_show_comment_counter'=> '1',
'blog_show_comment_form'=>'1',
'blog_show_hits' => 1,
'cat_columns_leading_blog'=> 1,
'cat_columns_leading_blogs'=> 1,
'cat_columns_secondary_blogs' => 2,
'comment_engine' => 'local',
'diquis_account' => 'pavothemes',
'facebook_appid' => '100858303516',
'facebook_width'=> '600',
'comment_limit'=> '10',
'auto_publish_comment'=>0,
'enable_recaptcha' => 1,
'recaptcha_public_key'=>'6LcoLd4SAAAAADoaLy7OEmzwjrf4w7bf-SnE_Hvj',
'recaptcha_private_key'=>'6LcoLd4SAAAAAE18DL_BUDi0vmL_aM0vkLPaE9Ob',
'rss_limit_item' => 12,
'keyword_listing_blogs_page'=>'blogs'
);
}
}
?>
Try changing:
$data = array(
'sort' => 'b.`created`',
'order' => 'DESC',
'start' => 0,
'limit' => $setting['limit']
);
to:
$data = array(
'filter_category_id' => 35,
'sort' => 'b.`created`',
'order' => 'DESC',
'start' => 0,
'limit' => $setting['limit']
);
I did some research on opencart and I think this should work. Initially, I didn't see the following code, which checks for a filter_category_id in the getListBlogs() function:
if( isset($data['filter_category_id']) && $data['filter_category_id'] ){
$sql .= " AND b.category_id=".(int)$data['filter_category_id'];
}

Dynamically construct SQL search query?

I am trying to build a search query based on the input from users, but I am having problems with the AND and WHERE keywords. Here is the code:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = $key . ' = ' . $value;
}
}
}
The output looks like this:
Array
(
[0] => gender = masculine
[1] => level = low
[2] => status = future
)
If no option is selected, it defaults to 'all' and it is excluded from the $where[].
I need to achieve this, or anything similar:
Array
(
[0] => WHERE gender = masculine
[1] => AND level = low
[2] => AND status = future
)
The WHERE must be appended only if one or more options have been selected and the AND must be appended only if two or more options have been selected.
In the code I am using I have 9 search inputs. To keep it clear I only displayed three in the snippet. Can you please help me figure this out?
Try this:I think you need the whereClause in string not in array,here you can choose any one from two and remove the other one.
<?php
$where=array();$flag=0;// use flag to identify the where/and
$whereClause="";
$criteria = array('gender' => "masculine", 'level' => "low", 'status' => "future");
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($flag == 0){
$where[] = " WHERE " .$key . ' = ' . $value;//if you need array
$whereClause='WHERE '.$key . ' = "' . $value.'"';//if you need string
}else{
$where[] = " AND " .$key . ' = ' . $value;
$whereClause .=' AND '.$key . ' = "' . $value.'"';
}
$flag++;
}
}
echo "<pre>";
print_r($where);
echo "</pre>";
echo $whereClause;
?>
You can do this :
$query = 'SELECT * FROM candidate ';
$where='';
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($where=='')
$where='WHERE '.$key . ' = ' . $value;
else
$where.=' AND '.$key . ' = ' . $value;
}
}
$query.=$where; //final query
You can use simple switch statement too
<?
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value)
{
if ($value !== 'all')
{
switch ($key)
{
case 1:
{
$query = " WHERE " .$key . ' = ' . $value;
break;
}
case 2:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
case 3:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
}
$where[] = $query;
}
}
}
You need to put one incrementer ($inc) and then put the conditions as:
$inc=1;
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($inc==1){
$where[] = 'Where '.$key . ' = ' . $value.'';
}else{
$where[] = 'AND '.$key . ' = ' . $value.'';
}
$inc++;
}
}
In My view there is one more clean way of achiving this:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array("Where 1=1");
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = 'AND '.$key . ' = ' . $value.' ';
}
}
}

Categories