I am created form to select value to display in my page table.Below is my code to select multiple values and search to display, but it is not displaying the selected values (type and dates) in multiple dropdownlist. Anyone can help me solve this problem? Thanks.
My frontend coding:
<div class="box inverse">
<div class="row">
<div class="col-lg-12">
<header>
<h5>Search</h5>
</header>
<form id="transaction_search">
<div class="form-group">
<div class="col-lg-12">
<div class="col-lg-3">
</div>
<div class="col-lg-12">
<div class="form-group">
<div class="col-lg-12">
<label for="text1" class="form-group control-label col-lg-2"><?php echo $language['type']; ?>:</label>
<div class="col-lg-5">
<select id="select_type" class="form-group form-control required"">
<option value="transfer" selected><?php echo $language["transfer"]; ?></option>
<option value="withdraw"><?php echo $language["withdraw"]; ?></option>
<option value="upgrade"><?php echo $language["upgrade"]; ?></option>
<option value="register"><?php echo $language["register"]; ?></option>
<option value="receive"><?php echo $language["receive"]; ?></option>
</select>
</div>
</div>
</div>
<div class="col-lg-12 form-group">
<label for="text1" class="form-group control-label col-lg-2">Date Range:</label>
<div class="col-lg-2">
<?php echo custom_period_opt(); ?>
</div>
<label for="text1" class="form-group control-label col-lg-2">Date Created:</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="start_date" name="start_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
<label for="text1" class="form-group control-label col-lg-2">To</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="end_date" name="end_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-12" style="text-align:center; padding-bottom:10px; padding-top:10px;">
<button id="search" type="button" class="btn btn-sm btn-primary" onclick="search_('transaction_search','transaction_result','transaction_table')">Search</button>
<button id="clear" type="button" class="btn btn-sm btn-default" onclick="clearData()">Clear</button>
</div>
<div class="body" id="transaction_result" style="overflow:auto;">
</div><!--body-->
</form>
</div>
</div>
My backend coding (This is part of coding I try to select "Withdraw" option to test output, but did't display any data in the table. This coding is want to select "withdraw" and select what I choose the "date"):
<?php
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
$select_type = $_POST['select_type'];
unset($arr_val['loc']);
unset($arr_val['action']);
unset($arr_val['select_type']);
$tbl_name = 'withdrawal_record';
if ($action == 'search' && $select_type == 'withdraw' ) {
if ($_POST['select_type'] != '' || $_POST['start_date'] != '' || $_POST['end_date'] != '' ) {
$sql = 'SELECT * FROM ' . $tbl_name . ' WHERE id is not null';
if($_POST['start_date']!='' && $_POST['end_date']!= '') {
$sql .=' and a.created between "' . date('Y-m-d', strtotime($_POST['start_date'])) . '" and "' . date('Y-m-d', strtotime($_POST['end_date'])) . '"';
}
$result_arr['sql'] = $sql;
$result_arr = get_data_list($sql);
$i = 1;
echo '<table id="dataTable_1" class="dataTable table table-bordered table-condensed table-hover table-striped" style="padding:0px;" border="1">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>';
foreach ($result_arr as $rs_search) {
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $rs_search['created'] . "</td>";
echo "<td>" . $rs_search['withdraw_amount'] . "</td>";
echo '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
}
}
?>
Below is jquery function:
function search_(form_id, div_id, act_file) {
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
$.ajax({
//dataType: 'json',
type: 'POST',
url: '?f=' + act_file,
data: form_data,
beforeSend: function() {
show_overLay();
$('#' + div_id).html('');
},
success: function(data) {
hide_overLay('');
if (data) {
$("#" + div_id).append(data);
$('.dataTable').dataTable({
pageLength: 25,
destroy: true
});
} else {
hide_overLay("Please fill in the field.");
}
//console.log(data);
}
});
}
Below is my "withdrawal_record" table:
withdrawal_record
Below is my output, and didn't show the data what I select. Actually I want to select date between 04/11/19 and 07/11/19 and select type is "Withdraw" :
Output 1
If success , that will show like below the output picture:
Output 2
Error output:
Output 3
In html add multiple attribute to select :
<select id="select_type" class="form-group form-control required" multiple>
In JQuery make these changes:
Remove these :
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
And in Ajax request:
Remove these lines:
data: form_data,
Add these lines:
data:{action:"search","loc":$("#select_type").val().toString()},
In PHP remove these lines :
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
And these lines instead:
$loc = $_POST['loc'];
$action = $_POST['action'];
$loc =explode(","$loc );
foreach($loc AS $val)
{
echo $val; // your locations
}
Related
How can I load data from my database into a select box? This select box is dependent to another select box.
I will need to update the details of my products. When I click the specific product in the table, the product details will load on my update view. Everything is almost fine except for one select box namely size select box, which the data didn't show.
I tried many solutions but none of them works.
This is my product table view:
<div class="col-sm-10" id="main">
<div class="table-wrapper">
<div id="content">
<legend class="text-danger"><h1>Product List</h1></legend>
<?php $tableAttr = array(
'table_open' => '<table class="table table-responsive table-striped table-hover" id="item_tbl">',
);
$item_table = $this->table->set_heading('No.','PRODUCT CODE','PRODUCT DESCRIPTION','BRAND', 'CATEGORY', 'SIZE','ORIGINAL PRICE','ACTION');
$item_table = $this->table->set_template($tableAttr);
$num = 0;
foreach ($items as $item) {
$itemName = urlencode($item->prod_desc);
$num++;
$item_table = $this->table->add_row($num, $item->prod_code, $item->prod_desc, $item->brand_name,$item->category_name,$item->size,'₱'. $item->original_price,"
<a href='".base_url("item/update/$itemName")."'><button class='btn btn-info btn-sm'>EDIT</button></a>
");
}
echo $this->table->generate($item_table); ?>
</div>
</div>
</div>
So when I click edit button it will another form the product_update_view.php:
<div class="col-sm-10" id="main" style="padding: 20px;">
<?php echo form_open("item/item_update/$item->prod_id");
echo form_fieldset('<h3 class="text-info">Update Item</h3>'); ?>
<input type="hidden" name="cur_code" value="<?php echo $item->prod_code ?>">
<input type="hidden" name="cur_name" value="<?php echo $item->prod_desc ?>">
<input type="hidden" name="cur_category" value="<?php echo $item->category_name ?>">
<input type="hidden" name="cur_brand" value="<?php echo $item->brand_name ?>">
<input type="hidden" name="cur_size" value="<?php echo $item->size ?>">
<input type="hidden" name="cur_price" value="<?php echo $item->original_price ?>">
<div class="form-group">
<label for='prod_code'>Product Code:</label>
<input type="text" name="up_code" class="form-control" value="<?php echo $item->prod_code; ?>">
</div>
<div class="form-group">
<label for='prod_name'>Product Description:</label>
<input type="text" name=up_name" class="form-control" value="<?php echo $item->prod_desc; ?>">
</div>
<div class="form-group">
<label for='prod_name'>Brand:</label>
<select name="brand" class="form-control">
<option value="Select Brand" selected="selected">Select Brand</option>
<?php foreach($brand as $br):?>
<option value="<?php echo $br->brand_id; ?>" <?php if ($br->brand_id == $item->brand_id) {echo "selected='selected'";} ?>><?php echo $br->brand_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="category">Category</label>
<select class="form-control" name="category" id="category">
<option value="Select Brand"> Select Category</option>
<?php foreach($category as $cat): ?>
<option value="<?php echo $cat->category_id; ?>" <?php if ($cat->category_id == $item->category_id) {echo "selected='selected'";} ?>><?php echo $cat->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="sizes">Size:</label>
<select class="form-control" name="category" id="sizes">
<option value="Select size"> Select Size</option>
</select>
</div>
<div class="form-group">
<label for='prod_price'>Price:</label>
<input type="text" name="price" class="form-control" value="<?php echo $item->original_price; ?>">
</div>
<div class="form-group">
<input type="submit" name="submit_account" class="btn btn-primary" value="Save" >
</div>
</div>
<script src="<?php echo base_url() ?>dropdown/js/jquery.js"></script>
<script src="<?php echo base_url() ?>dropdown/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#category').on('change', function(){
var category_id = $(this).val();
if(category_id === '')
$.ajax({
url:"<?php echo base_url() ?>welcome/get_sizes",
type: "POST",
data: {'category_id' : category_id},
dataType: 'json',
success: function(data){
$('#sizes').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
</div>
<?php echo form_close(); ?>
The controller (item.php):
public function update($name) {
$this->load->model('Dependent_model', 'dep_model', TRUE);
$this->load->model('brand_model');
$data['category'] = $this->dep_model->get_category_query();
$data['brand'] = $this->brand_model->getBrandName();
$this->load->model('item_model');
$data['item'] = $this->item_model->item_info($name);
$this->load->view('header');
$this->load->view('side_menu');
$this->load->view('product_update_view.php',$data);
$this->load->view('footer');
}
The controller of dependent select box (welcome.php):
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Dependent_model', 'dep_model', TRUE);
}
public function index()
{
$data['category'] = $this->dep_model->get_category_query();
$this->load->view('new_product', $data);
}
public function get_sizes()
{
$category_id = $this->input->post('category_id');
$sizes = $this->dep_model->get_sizes_query($category_id);
if(count($sizes)>0)
{
$pro_select_box = '';
$pro_select_box .= '<option value="Select Size">Select Size</option>';
foreach ($sizes as $sz) {
$pro_select_box .='<option value="'.$sz->size_id.'">'.$sz->size.'</option>';
}
echo json_encode($pro_select_box);
}
}
}
Models (item_model.php):
public function item_info ($itemName) {
$this->load->database();
$this->db->select('products.*,category.category_name,sizes.size,brand.brand_name')
->from('products')
->from('category');
$this->db->from('sizes');
$this->db->from('brand');
$this->db->where('products.category_id = category.category_id');
$this->db->where('products.size_id = sizes.size_id');
$this->db->where('products.brand_id = brand.brand_id');
$this->db->where('prod_desc', urldecode($itemName));
$result=$this->db->get();
return $result->row();
}
The dependent select box model (dependent_model):
<?php
class Dependent_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get_category_query()
{
$query = $this->db->get('category');
return $query->result();
}
public function get_sizes_query($category_id)
{
$query = $this->db->get_where('sizes', array('category_id' => $category_id));
return $query->result();
}
}
The problem is it does not show the size of the specific product in product_update view.
Replace this jquery.
<script src="<?php echo base_url() ?>dropdown/js/jquery.js"></script>
<script src="<?php echo base_url() ?>dropdown/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var cat_id = $("#category option:selected").val();
if(cat_id != '')
$.fn.ajaxCall(cat_id);
ajaxCall(category_id);
$('#category').on('change', function(){
var category_id = $(this).val();
if(category_id != '')
$.fn.ajaxCall(category_id);
});
$.fn.ajaxCall = function(category_id){
$.ajax({
url:"<?php echo base_url() ?>welcome/get_sizes",
type: "POST",
data: {'category_id' : category_id},
dataType: 'json',
success: function(data){
$('#sizes').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
}
});
</script>
I'm having a problem with inserting data in my MySQL db table from an array. I have a form and an array which stores submitted values and its contents I display in a html table. In each table row there are values from one submit and a button which deletes the row with jQuery.
The problem is I also need the functionality to select a row from the html table and insert in my database table. I would like a button on each row's end that when clicked would insert the rows contents in my database table, similar to what i have now with deleting a row from my html table.
Deleting can be done with simple jQuery, but with this I have no idea how to continue, thanks for answers in advance.
This is how far i have gotten:
<div class="row">
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> ";
echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
</script>
You might want something like this
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
// insert all inputs to an a new array
$newInfo = array($_POST['code'], $_POST['title'], $_POST['number'], $_POST['value'], $_POST['retailvalue']);
// push the new array to session variable 'info'
array_push($_SESSION['info'], $newInfo);
// as you already have, loop thru each session info
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr><td></td>";
// echo each value to table cells
foreach($_SESSION['info'][$i] as $value){
echo "<td>".$value."</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\"></i>Delete</a></td> ";
echo "</tr>";
}
}
Plus the condition for checking error on retail value is wrong if you want it to be smaller than inventory value. Please double check
I decided to use Ajax to post the data to Database.
You could see that I used javascript method called postToDatabase to post the data and the data has been passed as arguments to the method.
Check out the code below.
<?php
// your database connection and database selection using PDO ( Safe and better to use PDO)
//BEGINNING OF DATABASE CONNECTION
$servername = "localhost";
$username = "root";
$password = "password";
$db_name = "db";
$db_engine = 'mysql';
try {
$conn = new PDO("$db_engine:host=$servername;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{ echo "Connection failed: " . $e->getMessage(); }
// END OF DATABSE CONNECTION
//DATA POSTED VIA AJAX
$code = trim($_POST["code"]);
$title = trim($_POST["title"]);
$number = trim($_POST["number"]);
$value = trim($_POST["value"]);
$retailValue = trim($_POST["retailvalue"]);
// BEGINNING OF INSERT QUERY
$sql = $conn ->prepare("INSERT INTO books (code, title, number, value, retailvalue) VALUES (?, ?, ?, ?, ?)"); // ? WILL BE REPLACED BY THEIR RESPECTIVE VALUES IN THE EXEC() METHOD.
$sql->execute(array($code, $title, $number, $value, $retailValue));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div id="success_msg" class="alert alert-success fade in" style="display:none;">
×
<strong>Success!</strong> Data Saved.
</div>
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<form name="form">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
$vals .= "'$key',";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> "; ?>
<td>
<a onclick="postToDatabase(<?php echo substr($vals,0,-1); $vals=NULL; ?>);" class="add" href="#"> <i class="fa fa-plus" aria-hidden="true"></i>
</a>
</td>
<?php echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</form>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
</div>
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
function postToDatabase(code, title,number,value,retailvalue){
$.ajax({
type: "POST",
url: 'index.php',
data: "code=" + code + "&title=" + title + "&number=" + number + "&value=" + value + "&retailvalue=" + retailvalue,
success: function (msg) {
$('#success_msg').show();
}
});
}
</script>
</body>
</html>
I have searched a long way for the result but still no success on this. I am trying to select radio button and hence showing its result on same page but my query somehow not getting records for the same. It says MySQL "QUERY EMPTY". Please let me know where am I doing wrong. Here is my code for that. A help would be highly appreciated.
PHP
<?php
include 'blocks/headerInc.php' ;
$errmsg = $module_id = $query = $date_from = $date_to = $sql1 = "";
//Search section start here
/*$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 ";
if (isset($_REQUEST['submit'])) {
if (!empty($_REQUEST['date_from'])) {
$date_from = date("Y-m-d", strtotime($_REQUEST['date_from']));
}
if (!empty($_REQUEST['date_to'])) {
$date_to = date("Y-m-d", strtotime($_REQUEST['date_to']));
}
if (!empty($date_to) && empty($date_from)) {
$errmsg = "Please select valid date range.";
}
if (!empty($date_to) && (strtotime($date_from) > strtotime($date_to))) {
$errmsg = "Please select valid date range.";
}
if ($errmsg == '') {
if (!empty($date_to) && (strtotime($date_from) <= strtotime($date_to))) {
$sqlQuery .= " AND created_on BETWEEN '$date_from' AND '$date_to'";
}
$sqlQuery .= " order by id DESC";
}
$date_from = date("m/d/Y", strtotime($date_from));
$date_to = date("m/d/Y", strtotime($date_to));
$date_from = $date_from != '01/01/1970' ? $date_from : '';
$date_to = $date_to != '01/01/1970' ? $date_to : '';*/
if (isset($_POST['users']) && $_POST['users'] == 'approved') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3 and status = 1");
//$result = ($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
} elseif (isset($_POST['users']) && $_POST['users'] == 'unapproved') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3 and status = 0");
//$result = mysql_query($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
} elseif (isset($_POST['users']) && $_POST['users'] == 'all') {
$sql1 = mysql_query("SELECT * FROM tbl_user WHERE type =3");
//$result = mysql_query($sql1);
while ($row = $sql1->fetch_assoc()) {
$users[] = $row;
}
}
//}
?>
HTML:
<div class="container pagecontainer">
<!-- Static navbar -->
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<?php include 'blocks/leftnavInc.php' ; ?>
</div>
</div>
<div class="col-xs-12 col-sm-9 page-right">
<div class="panel panel-primary">
<div class="panel-heading">Search Registered Candidate</div>
<div class="panel-body">
<div class="column col-sm-offset-0">
<?php if($errmsg!="") echo "<div class='error'>".ucwords($errmsg)."</div>"; ?>
<form class="form-horizontal" method="get" action="">
<div class="form-group">
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label">Date From:</label>
</div>
<div class="col-md-8">
<div class="input-group date">
<input class="form-control datepicker" data-val="true" data-val-date="The field Dob must be a date." data-val-required="The Dob field is required." id="Dob" name="date_from" placeholder="Date From" type="text" value="<?php echo $date_from ; ?>" >
</div>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label">Date To:</label>
</div>
<div class="col-md-8">
<div class="input-group date">
<input class="form-control datepicker" data-val="true" data-val-date="The field Dob must be a date." data-val-required="The Dob field is required." id="Dob" name="date_to" placeholder="Date To" type="text" value="<?php echo $date_to ; ?>" >
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<div class="col-md-8 text-left">
<button type="submit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Search</button>
<button type="reset" onClick="javascript:window.location.href='reportRegisteredUsers.php'" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4">
<label for="username" class="control-label"> </label>
</div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Report:Registered Candidate</div>
<div class="panel-body">
<input type="radio" name="users" value="all" checked="checked"> All Candidates<br>
<input type="radio" name="users" value="approved"> Approved Candidates<br>
<input type="radio" name="users" value="unapproved"> Unapproved Candidates<br> </form>
<div class="column col-sm-offset-0">
<table id="example" class="table table-striped table-hover table-bordered dataTableReport dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>S.No.</th>
<th>Email ID</th>
<th>SBI Employee ID</th>
<th>Name</th>
<th>Mobile No.</th>
<th>Date of Birth</th>
<th>Registration Date</th>
</tr>
</thead>
<tbody>
<?php
$sqr = $db->query($sql1);
//print_r($sqr);
//$i = 1 ;
//$sq = $db->query($sqlQuery);
$i = 1 ;
if($db->affected_rows > 0)
{
while($row=mysql_fetch_array($sqr))
{
extract($row);
?>
<tr>
<td><?php echo $i ; ?></td>
<td><?php echo $email ; ?></td>
<td><?php echo $employee_id ; ?></td>
<td><?php echo $first_name." ".$middle_name." ".$last_name ; ?></td>
<td><?php echo $mobile ; ?></td>
<td><?php if($dob !='1970-01-01'){echo date("d-m-Y", strtotime($dob)) ; }?></td>
<td><?php echo date("d-m-Y", strtotime($created_on)) ; ?></td>
</tr>
<?php $i++;}} ?>
</tbody>
</table>
</div>
</div>
</div>
<div>
<button type="reset" onClick="javascript:history.go(-1)" class="btn btn-danger"><i class="glyphicon glyphicon-ban-circle"></i> Go Back</button>
</div>
<!--/row-->
</div>
<!--/.sidebar-offcanvas-->
</div>
</div>
<?php include 'blocks/footerInc.php'; ?>
Does this need to be strictly PHP and MySQL? Can we include some JavaScript/jQuery? While this doesn't answer your question directly, I hope it helps.
For your issue, I would detect the change event of your radio field and fire off a quick jQuery $.post to process the selection.
When your JavaScript sends a POST request to your PHP, you would run your PHP logic and return (or echo) the result. This can then be "digested" by your JavaScript. Here is a simple/rough example using jQuery and PHP. Adapt to your needs:
<script>
// # on ready
$(function() {
// # current document - assumes you'll be submitting to self
var self = document.location.href;
// # when changing the user radios
$('input[type=radio][name=users]').change(function() {
// # grab the value of the radio and create a js array to post
var postData = {'users': $(this).val()};
// # post the postData to your PHP
$.post(self, postData).done(function(data, status, xhr) {
// # assumes you're returning JSON data
data = jQuery.parseJSON(data);
// # add your logic here
console.log('POST Response', data);
// # update an element with the returned data or response:
$('#example').before('<div>'+ data +'</div>');
});
});
});
</script>
Regarding your PHP code, as other users have suggested, you're using mysql_ functions that are no longer supported on modern versions of PHP. You're quickest and dirtiest adjustment, without rewriting everything, is to use mysqli_ functions (notice the additional 'i').
You're already listening for the $_POST['users'] parm, so the only addition I would recommend is to actually use that $users[] array. I could get into re-writing the PHP so it makes sense, but here is a quick adjustment to your existing code:
<?php
$users = array();
if(isset($_POST['users']) && $_POST['users'] == 'approved'){
$query = "SELECT * FROM tbl_user WHERE type = 3 AND status = 1";
} else if(isset($_POST['users']) && $_POST['users'] == 'unapproved') {
$query = "SELECT * FROM tbl_user WHERE type =3 and status = 0";
} else if (isset($_POST['users']) && $_POST['users'] == 'all') {
$query = "SELECT * FROM tbl_user WHERE type =3";
}
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
// # encode your $row array into JSON and echo for JavaScript
echo json_encode($users);
// # free result set
$result->free();
}
?>
While this isn't a complete solution, I hope it points you in the right direction.
A couple things to note - you'll need to adjust your MySQL connection code if you're to use mysqli_ functions. You'll also need to include jQuery (ideally from CDN) for that JavaScript to work (or you could rewrite it to not use a library like jQuery). This should return the results of your query to your JavaScript. The result should be available as "data" in your js. I've added a console.log so you can view the response in your inspector.
Good Luck!
When i am trying to select option value form row one there's no problem but if i add more and select optional value in second row then its getting conflict first. Every time when you select optional value then only first row conflict i want first row change while changing first select option . Second row select change only second row values.
index.php
<?php
if(!empty($_POST["save"])) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$itemCount = count($_POST["item_name"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
$result = mysql_query($sql);
if(!empty($result)) $message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php if(isset($message)) { echo $message; }?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index:item_index},`
success:function(result){
alert(result);
$('#div1').html(result);
}
});
}
</script>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$result = mysql_query("select * from item");
while($row=mysql_fetch_assoc($result))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</DIV>
<DIV class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></DIV>
</DIV>
and getsaleinfo.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$supplier= $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
if($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" >
</div>
<?php }
?>
database
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(255) NOT NULL,
`item_price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `item` (`id`, `item_name`, `item_price`) VALUES
(1, 'hello', 21),
(2, 'hi', 22);
try this...
$('body').on('change','#item_index',function() { //works for ajax loaded contents
var id = $("#item_index").val();
var formid = new FormData();
formid.append('item_index',id);
$.ajax({
url : 'getsaleinfo.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formid,
type : 'post',
success : function(data){
alert(result);
$('#div1').html(result);
//document.getElementById("div1").innerHTML=data;
}
});
}
insted of onchange call this will do...
When you change the selection in the dropdown list, it sends the request to the server:
getsaleinfo.php with item_index:'hello'
That executes
select * from item where item_name='hello' (one line)
That sends
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini"
value="<?php echo $row['item_price'];?>" >
</div>
back to the caller.
The javascript puts that whole thing inside #div1 replacing whatever was there.
From what I'm gathering, addMore() is loading the whole of input.php every time and appending it to #product.
First of all that means you're repeated adding the jquery and function definition, but secondly (and the main problem) - each one adds a NEW div with ID=div1.
When you call
$('#div1').html(result)
in your salesdetail function, that just refers to the first one (since according to HTML you can only have one instance of each ID and the others are ignored.
/*------------------------index.php--------------------------*/
<?php
if (!empty($_POST["save"])) {
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$itemCount = count($_POST["item_index"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for ($i = 0; $i < $itemCount; $i++) {
if (!empty($_POST["item_index"][$i]) || !empty($_POST["unit_price"][$i])) {
$itemValues++;
if ($queryValue != "") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_index"][$i] . "', '" . $_POST["unit_price"][$i] . "')";
}
}
$sql = $query . $queryValue;
if ($itemValues != 0) {
$result = mysql_query($sql);
if (!empty($result))
$message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
var cnt = 1;
function addMore() {
$("<DIV>").load("input.php?cnt=" + cnt, function() {
$("#product").append($(this).html());
cnt++;
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item) {
jQuery(':checkbox', this).each(function() {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php
if (isset($message)) {
echo $message;
}
?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
/*------------------------input.php--------------------------*/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index, item_id)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index: item_index, item_id: item_id},
success: function(result) {
alert(result);
$('#div_' + item_id).html(result);
}
});
}
</script>
<?php $_REQUEST['cnt'] = (isset($_REQUEST['cnt'])) ? $_REQUEST['cnt'] : 0; ?>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_REQUEST['cnt']; ?>" /></DIV>
<DIV class="float-left"><select name="item_index[]" id="item_index_<?php echo $_REQUEST['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_REQUEST['cnt']; ?>');" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$result = mysql_query("select * from item");
while ($row = mysql_fetch_assoc($result)) {
echo "<option>" . $row['item_name'] . "</option>";
}
?>
</select></DIV>
<DIV class="float-left" id="div_<?php echo $_REQUEST['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_REQUEST['cnt']; ?>" name="unit_price[]" /></DIV>
</DIV>
getsaleinfo.php
/*------------------------getsaleinfo.php--------------------------*/
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$supplier = $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
$_REQUEST['item_id'] = (isset($_REQUEST['item_id'])) ? $_REQUEST['item_id'] : '';
if ($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<input type="text" name="unit_price[]" id="unit_price_<?php echo $_REQUEST['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" >
</div>
<?php }
?>
I have a form that has a select field that loads the options dynamically from a db result query. Here is what the code looks like. See the description text input afterwards? I need the code to return the description of the item selected under productID. How do I go about this? Thanks very much for all replies.
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" value=""/>
</div>
</div>
You can do this in 2 ways:
First way is by redirecting the page having a $_GET parameter which will contain the product id:
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1"
onchange="document.location=\'my-page.php?pid=\' + this.value">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'"';
// LATER EDIT
if(isset($_GET['pid']) && $_GET['pid'] == $res['productID'])
echo 'selected="selected"';
// END LATER EDIT
echo '>';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php
if(isset($_GET['pid']) && is_numeric($_GET['pid'])) {
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_GET['pid']) . "'");
$row = mysql_fetch_assoc($sql);
}
?>
<input type="text" name="description" value="<?=$row['description']?>"/>
</div>
</div>
Second way is to have an ajax call and fill description input dynamically, without refresing the page
// this is the JS code
$(document).ready(function(){
$('#user').change(function(){
$.POST("my-ajax-call-page.php",
{pid: $("#user").val()},
function(data){
$('input[name="description"]').val(data.description);
}, "json");
});
});
and your my-ajax-call-page.php should be like this:
<?php
include("mysql-connection.php");
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_POST['pid']) . "'");
$row = mysql_fetch_assoc($sql);
echo json_encode("description" => $row['description']);
?>
You will find many examples and documentation for using jQuery library on jQuery library website
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1" onchange="showDesc()">';
$desHTML = "";
echo "<option value='0'>Please select</option>"
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res["SKU"] ;
echo'</option>';
$desHTML .="<div class'descBox' id='".$res['productID']."' style='display:none'>".$res['description']."</div>";
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php echo $desHTML; ?>
</div>
</div>
Now create one js function and call on onchange of select box.
Js function Hint:
$(".descBox").hide();
$("#"+selectedItemValue).show();
Let me know if you need any help for JS function.
You haven't shown us your SQL query, but I assume that you have a column named description and you are selecting this column in your query too.
So then, you can use jQuery to insert description of selected item to input
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
$js_array = array(); // This variable will contain your Javascript array with descriptions
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
// Fill your array with descriptions; ID of item will be the index of array
$js_array[$res['productID']] = $res['description'];
}
echo'</select>';
?>
<script>
var description;
<?php
foreach($js_array as $description => $id)
{
echo("description['".$id."'] = '".$description."';\n");
}
?>
$(document).ready(function(){
$('#user').change(function(){
$("#description").val(description[$('#user').val()]);
})
});
</script>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" id="description" value=""/>
</div>
</div>
Be sure to not forget to add id attribute to your input type="text"