DataTables Sorting based on SQL Statement - php

I have a textbox for users to insert their SQL statement. I need to sort my DataTables based on the Asc and Desc in that SQL statement. When users see the datatable content it will either be in Asc or Desc depending on whatever they type in the SQL statement. How do I go about with it
<label> Query </label>
<textarea class="form-control" name="sql_input" rows="5" id="comment" placeholder="Select statement input here..."><?php if (isset($_POST['submit'])){ echo $_POST['sql_input'];} ?></textarea>
<br><label> X-Axis </label> <input type="text" name = "xaxis" class="form-control" id="xaxis" placeholder="X Axis e.g `id`" value = <?php if (isset($_POST['submit'])){ echo $_POST['xaxis'];} ?>>
<br><label> Y-Axis </label> <input type="text" name = "yaxis" class="form-control" id="yaxis" placeholder="Y Axis e.g `created_by`" value = <?php if (isset($_POST['submit'])){ echo $_POST['yaxis'];} ?>>
<table class="table table-striped table-bordered table-hover" id="dataTable_table">
<thead>
<tr>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{
foreach((array)$row1 as $key=>$val)
{
?>
<th><?php echo $key ?></th>
<?php
}
break;
}
?>
</tr>
</thead>
<tbody>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{ ?>
<tr>
<?php
foreach((array)$row1 as $key=>$val)
{ ?>
<th><?php echo $val ?></th>
<?php
} ?>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<link href="scripts/dataTables/dataTables.bootstrap.css" rel="stylesheet">
<script src="scripts/dataTables/jquery.dataTables.js"></script>
<script src="scripts/dataTables/dataTables.bootstrap.js"></script>
<script>
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var select_value = $('#select_value').val();
var select_column = $('#select_column').val();
var column_index = '';
//var column = data[1] || 0; // use data for the age column
if ( select_value == '' || select_column == '' )
{
return true;
}
else {
//get the column name of data table
var column = 0;
$('#dataTable_table thead tr th').each(function(){
if( $(this).text() == select_column.toString())
{
return false;
}
column = column + 1;
});
column = data[column] || 0;
if(column!==0 && column.indexOf(select_value.toString()) >= 0)
{
return true;
}
}
return false;
}
);
$.fn.dataTableExt.sErrMode = 'throw';
$(document).ready(function () {
var table = $('#dataTable_table').DataTable();
$('#select_value').keyup( function() {
table.draw();
});
});
</script>

Related

Update multiple record with single query in database using php [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I am making an invoice in PHP where multiple products are inserted at once into one table and there grand total goes to another table. I am trying to UPDATE the invoice in MYSQL and PHP. When I press the submit button, the multiple records data from the form goes to the update.php but the query does not run.
database.php
<?php
$connect = mysqli_connect('localhost','root','','invoice');
if (!$connect){
die("Connection failed: " . mysqli_connect_error());
}
?>
edit_invoice.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,tr,td,th { border: 1px black solid;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Back to Invoice List<br><br>
<?php
include('database.php');
$invoice_number = $_GET['invoice_number'];
$sql = "SELECT * from invoice where invoice_number = '$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query->num_rows > 0) {
// output data of each row
$fetch = $query->fetch_assoc();
}
?>
<form method="POST" action="update_invoice.php">
<table>
<thead>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Total</th>
<th>Action</th>
</thead>
<?php
$sql2 = "SELECT * from invoice_order where invoice_number = '$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2->num_rows > 0) {
// output data of each row
$srno = 1;
$count = $query2->num_rows;
for ($i=0; $i < $count; $i++) {
while($row = $query2->fetch_assoc()) {
?>
<tbody id="product_table">
<tr>
<td><input type="text" name="product[]" value="<?php echo $row["product"]; ?>"></td>
<td><input type="text" name="price[]" value="<?php echo $row["price"]; ?>"></td>
<td><input type="text" name="quantity[]" value="<?php echo $row["quantity"]; ?>"></td>
<td><input type="text" name="width[]" value="<?php echo $row["width"]; ?>"></td>
<td><input type="text" name="height[]" value="<?php echo $row["height"]; ?>"></td>
<td><input type="text" name="total[]" value="<?php echo $row["total"]; ?>" class="totalPrice" readonly></td>
<td><input type="button" value="X" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
<?php
}
}
} else {
echo "No Record Found";
}
?>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
<span>Invoice Date:<input type="date" value="<?php echo $fetch["invoice_date"]; ?>" name="invoice_date"></span>
<span>Invoice #:<input type="text" name="invoice_number" value="<?php echo $fetch["invoice_number"]; ?>" readonly></span>
<span>Select Customer:
<select name="to_user" class="form-control">
<option><?php echo $fetch["customer_id"]; ?></option>
<?php
include('database.php');
$sql = mysqli_query($connect, "SELECT * From customer");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['customer_id'] ."'>" .$row['customer_id'] ." - " .$row['customer_name'] ."</option>" ;
}
?>
</select>
</span>
</table>
<span>Grand Total<input type="text" name="grandtotal" id="grandtotal" value="<?php echo $fetch["grandtotal"]; ?>" readonly></span><br><br>
<span>Paid Amount<input type="text" name="paid" id="paid" value="<?php echo $fetch["paid"]; ?>"></span><br><br>
<span>Balance<input type="text" name="balance" id="balance" value="<?php echo $fetch["balance"]; ?>" readonly></span><br><br>
<input type="submit" name="send" value="Submit">
</form>
</body>
<script>
const table = document.getElementById('product_table');
table.addEventListener('input', ({ target }) => {
const tr = target.closest('tr');
const [product, price, quantity, width, height, total] = tr.querySelectorAll('input');
var size = width.value * height.value;
var rate = price.value * quantity.value;
if (size != "") {
total.value = size * rate;
}else{
total.value = rate;
}
totalPrice();
});
function add_fields() {
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="product[]"></td>' +
'<td><input type="text" name="price[]"></td>' +
'<td><input type="text" name="quantity[]"></td>' +
'<td><input type="text" name="width[]" value="0"></td>' +
'<td><input type="text" name="height[]" value="0"></td>' +
'<td><input type="text" name="total[]" class="totalPrice" readonly></td>' +
'<td><input type="button" value="X" onclick="deleteRow(this)"/></td>';
table.appendChild(row);
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
totalPrice();
}
function totalPrice() {
var grandtotal = 0;
var paid = 0;
$(".totalPrice").each(function() {
grandtotal += parseFloat($(this).val());
paid = grandtotal;
});
$("#grandtotal").val(grandtotal);
$("#paid").val(paid);
}
$(document).ready(function() {
$('#paid').on('input', function() {
grandtotal = $("#grandtotal").val();
paid = $("#paid").val();
balance = parseFloat(grandtotal) - parseFloat(paid);
$("#balance").val(balance);
})
});
</script>
</html>
Update_invoice.php
<?php
include('database.php');
if (isset($_POST['send'])) {
$product = $_POST['product'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$width = $_POST['width'];
$height = $_POST['height'];
$total = $_POST['total'];
$customer_id = $_POST['to_user'];
$invoice_date = $_POST['invoice_date'];
$invoice_number = $_POST['invoice_number'];
$grandtotal = $_POST['grandtotal'];
$paid = $_POST['paid'];
$balance = $_POST['balance'];
$amount_status = "";
if ($grandtotal == $paid) {
$amount_status = "Paid";
} elseif ($grandtotal == $balance) {
$amount_status = "Due";
} else {
$amount_status = "Partial";
}
// Start of Updating data to invoice_order table
for ($i = 0; $i < count($_POST['total']); $i++) {
if ($i <> count($_POST['total'])) {
$sql = "UPDATE invoice_order SET invoice_number = '$invoice_number' , product = '$_POST['product'][$i]', price = '$_POST['price'][$i]' , quantity = '$_POST['quantity'][$i]', width = '$_POST['width'][$i]' , height = '$_POST['height'][$i]' , total = '$_POST['total'][$i]' WHERE invoice_number='$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query) {
header('location: list_invoice.php');
} else {
echo "Unable to enter records in invoice_order table";
}
}
}
// End of updating data to invoice_order table
// Start of updating data to invoice table
$sql2 = "UPDATE invoice SET customer_id = '$customer_id', grandtotal = '$grandtotal', invoice_number = '$invoice_number', invoice_date = '$invoice_date', paid = '$paid', balance = '$balance', amount_status = '$amount_status' WHERE invoice_number='$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2) {
header('location: list_invoice.php');
} else {
echo "Unable to enter record in invoice table";
}
// End of updating data to invoice table
}
?>
The approach you are using is not the preferred way of doing the job. Use mysql prepare statement. This will make the code clean, easy to read and secured. Here is the link you can refer Mysql Prepared Statement in PHP

Insert and Update data in database at the same time

What i want- i want to insert data into database if no existing data, and update if the data already exist in database.
Problem - If i click submit button without enter new data, the data still insert into database.
This is my code so far:
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<?php
mysql_connect("localhost","root","");
mysql_select_db("cuba");
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
/*$sqlQuery = "REPLACE INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."')"; */
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) on DUPLICATE KEY UPDATE name='".$_POST['name'][$a]."', ic ='".$_POST['ic'][$a]."'";
mysql_query($sqlQuery)or die(mysql_error());
}
}
?>
<form action="" method="post">
<div class="b">
<?php
$a = 1;
$share = mysql_query("select *from a")or die(mysql_error());
while($share_papar = mysql_fetch_array($share))
{
?>
<table class="bb" style="border:1px solid #003;">
<tr>
<td width="200">Name</td>
<td> : <input type="text" class="input_teks" name="name[]" value="<? php echo $share_papar['name'];?>" />
</td>
</tr>
<tr>
<td>ic</td>
<td> : <input type="text" class="input_teks" name="ic[]" value="<?php echo $share_papar['ic'];?>" /></td>
</tr>
<tr>
<td>id</td>
<td> : <input type="text" class="input_teks" name="id[]" value="<?php echo $share_papar['id'];?>" id="akhir"/></td>
</tr>
<tr>
<td colspan="2" align="right" class="b_buang">Remove</td>
</tr>
</table>
<?php
}?>
</div>
<input type="submit" value="ss" name="hantar">
</form>
<span class="b_tambah">Add new group</span>
<script type="text/javascript">
$(function()
{
//nk clone
$('.b_tambah').on('click',function(e)
{
$(".b").find(".bb").last().clone(true).appendTo(".b");
alert( $(".bb:last").find("input[id=akhir]").last().val());
var m = $(".bb:last").find("input[id=akhir]").last();
m.val("");
});
//nk buang
$(".b_buang").click(function () {
if($('.bb').length < 2)
{
alert("Remove operation can be done if GROUP more than one");
}
else
{
$(this).parents(".bb").remove();
}
});
});
</script>
<!-- close clone Shareholders -->
</td>
I'm using jquery to clone form same with update form, then reset value to blank for input type name (id), so i can have non match id with existing data. But if i submit form without cloning those form, the data will insert into database. What i want is, no need to insert data into database if i dont cloning the new data and just update the existing. How i can achieve that..
Use this code
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
$name = $_POST['name'][$a];
$ic = $_POST['ic'][$a];
$name = $_POST['name'][$a];
$sel = mysql_query("select * from a where name = '$name' and ic = '$ic' ");
if(mysql_num_rows($sel) > 0){
//write update query
$fet =mysql_fetch_array($sel);
$auto_increment_id = $fet['id'];
$sqlQuery = " update a set name = '$name' , ic = '$ic' where id = '$auto_increment_id' ";
}
else {
// write insert query
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) ";
}
mysql_query($sqlQuery)or die(mysql_error());
}
}
first check the $_POST['name'] in SELECT query if it is exsits update in the query if not then insert into database
try replacing
for($a=1; $a<=count($_POST['name']); $a++)
to
for($a=0; $a < count($_POST['name']); $a++)
And also check validation
e.g.
if(isset($_POST['name'][$a]) && trim($_POST['name'][$a]) != "")
Finally.. This code save me..
if(isset($_POST['hantar']))
{
for($a=0; $a < count($_POST['name']); $a++)
{
if($_POST['name'][$a]=="")
{
}else
{
if($_POST['id'][$a]=="")
{
$sqlQuery = "INSERT INTO a (name,ic) VALUES ('".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' )";
mysql_query($sqlQuery)or die(mysql_error());
}
else
{
$sqlQuery = " update a set name = '{$_POST['name'][$a]}' , ic = '{$_POST['ic'][$a]}' where id = '{$_POST['id'][$a]}' ";
mysql_query($sqlQuery)or die(mysql_error());
}
}
}
}

Keeping Dynamic Table Rows shown after form post errors

I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.

jQuery Autocomplete with dynamic rows

I have the following jQuery code:
$(document).ready(function(){
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item").val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price").val(ui.item.CASE_PRICE);
} else {
$("#del_price").val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item").autocomplete(ac_config);
});
Which works fine for one line item, basically the line item takes an item name, which is the field you type in for autocomplete and then after selecting it fills the price field with either the unit price or case price from my DB. Now I want to have 18 of these rows which I set up through php to be del_item1, del_item2 etc. and when I tried the following code, the autocomplete works and it fills in the item fine, but the price field does not fill in, any ideas...?
$(document).ready(function(){
for (var i = 1; i < 19; i++) {
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item" + i).val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price" + i).val(ui.item.CASE_PRICE);
} else {
$("#del_price" + i).val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item" + i).autocomplete(ac_config);
});
Here is the php file that the JS references:
<?php
require_once "/home/default/support/default.php";
$dbh = showDB ();
$cities = array();
$sth = $dbh->prepare("SELECT * FROM purchase_items");
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$cities[]=$row;
}
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $city){
if((stripos($city['SKU'], $term) !== false) || (stripos($city['FAMILY'], $term) !== false) || (stripos($city['DESCRIPTION'], $term) !== false)){
// Add the necessary "value" and "label" fields and append to result set
$city['value1'] = $city['SKU'];
$city['value2'] = $city['FAMILY'];
$city['value3'] = $city['DESCRIPTION'];
$city['label'] = "{$city['FAMILY']} - {$city['DESCRIPTION']} ({$city['SKU']})";
$matches[] = $city;
}
}
$matches = array_slice($matches, 0, 100);
print json_encode($matches);
And here is the html side as requested above these are the 16 line items I'm working with, inside of a for loop the counter in the loop is $d:
if($d&1) { ?>
<div id="trow">
<? } else { ?>
<div id="trow" class="none">
<? } ?>
<div id="thirds" style="text-indent:5px;">
<input type="text" name="del_item<? echo("$d");?>" id="del_item<? echo("$d");?>" class="salesinput"
placeholder="Start typing item SKU, family, description..." style="text-align:left; width:95%;" />
</div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_price<? echo("$d");?>" id="del_price<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
<div id="lfsold" style="width:15%;"><input type="text" name="del_retail<? echo("$d");?>" id="del_retail<? echo("$d");?>" class="salesinput" /></div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_line<? echo("$d");?>" id="del_line<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
</div>

How to Create Multi level category hierarchy ( Category Tree ) - codeigniter

I want to simply create a multilevel category hierarchy from mysql
Category table:
________________________________________________________________________
| id | parent_id | name
————————————————————————————————————————————————————————————————————————
| 1 | 0 | Root
| 2 | 1 | Sub category of root
| 3 | 0 | category 1
| 4 | 3 | sub category of category 1
| 5 | 4 | sub category of first sub category of category 1
————————————————————————————————————————————————————————————————————————
php
public function getCategoryTree($level = 0) {
$rows = $this->db
->select(‘id,parent_id,name’)
->where(‘parent_id’, $level)
->get(‘categories’)
->result();
if (count($rows) > 0) {
foreach ($rows as $row) {
$rows = $this->getCategoryTree($row->id);
}
}
//return $rows;
}
echo $rows;
// output will be show as string so i have to return this string in a variable
Root
—Sub category of root
category 1
—sub category of category 1
——sub category of first sub category of category 1
The biggest problem in your code was that you were overwriting $rows inside your foreach loop.
Additionally, with a recursive solution, like you've gone for, it's important to keep track of what's been returned from the inner calls to the function/method.
Also, I've added an order by, to make sure the root category appears first.
protected function getCategoryTree($level = 0, $prefix = '') {
$rows = $this->db
->select('id,parent_id,name')
->where('parent_id', $level)
->order_by('id','asc')
->get('categories')
->result();
$category = '';
if (count($rows) > 0) {
foreach ($rows as $row) {
$category .= $prefix . $row->name . "\n";
// Append subcategories
$category .= $this->getCategoryTree($row->id, $prefix . '-');
}
}
return $category;
}
public function printCategoryTree() {
echo $this->getCategoryTree();
}
Try following...
<?php
$sql = "SELECT id, name, parent_id FROM category ORDER BY parent_id, id";
$results = mysqli_query($con,$sql) or die(mysqli_error()) ;
if($results)
{
while($result = mysqli_fetch_array($results))
{
$category['categories'][$result['id']] = $result;
$category['parent_cats'][$result['parent_id']][] = $result['id'];
}
}
?>
<?php
function getCategories($parent, $category)
{
$html = "";
if (isset($category['parent_cats'][$parent]))
{
$html .= "<ul>\n";
foreach ($category['parent_cats'][$parent] as $cat_id)
{
if (!isset($category['parent_cats'][$cat_id]))
{
$html .= "<li>".$category['categories'][$cat_id]['name']."</li> \n";
}
if (isset($category['parent_cats'][$cat_id]))
{
$html .= "<li>". $category['categories'][$cat_id]['name'] . " \n";
$html .= getCategories($cat_id, $category);
$html .= "</li> \n";
}
}
$html .= "</ul> \n";
}
return $html;
}
?>
Now call Recursive function to display all Category in Hierarchy:
<?php echo $data['category'] = getCategories(0, $category);?>
details info
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password,'test');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function getCategoryTree($level = 0, $prefix = '') {
$category = '';
$sql = "SELECT * FROM category WHERE parent_id = $level ORDER BY id asc";
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$category .= $prefix . $row['name'] . "<br/>";
$category .= getCategoryTree($row['id'], $prefix . '-');
}
}
return $category;
}
function printCategoryTree() {
echo getCategoryTree();
}
printCategoryTree();
?>
Table for this:
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL DEFAULT '0',
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
First create config.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = new mysqli($servername, $username, $password,'test');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Then create category.php.
<?php
require 'config.php';
if(isset($_POST['submit']))
{
$parent_id=$_POST['parent_id'];
$name=$_POST['name'];
global $db;
$db->query("INSERT INTO categories (name,parent_id) VALUES('$name','$parent_id') ") or die(mysql_error());
}
function categoryTree($parent_id = 0, $sub_mark = ''){
global $db;
$query = $db->query("SELECT * FROM categories WHERE parent_id = '$parent_id' ORDER BY name ASC ");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['id'].'">'.$sub_mark.$row['name'].'</option>';
categoryTree($row['id'], $sub_mark.'---');
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST"><select name="parent_id">
<option value="0">Select Category</option><?php categoryTree(); ?>
</select>
Category : <input name="name" type="text" />
<input name="submit" type="submit" value="Submit" /></form>
</body>
</html>
Create a file add.php
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery-3.2.1.js"></script>
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery.validate.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.css" rel="stylesheet" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?=$this->config->item('css_path')?>bootstrap.min.css">
<html>
<head>
<div id="myDropdown" class="dropdown-content">
Category Form
User Listing
</div>
<div align="center"><h3>Category Form</h3></div>
</head>
<body>
<form id="signup_form" method="post" action="" enctype="multipart/form-data" >
<table border="1" align="center" width="450">
<tr>
<td>Category Name</td>
<td>
<input type="text" id="category_name" name="category_name" onkeypress="return isChar(event)" value="<?php echo !empty($editRecord[0]->category_name) ? $editRecord[0]->category_name :'' ?>" class="form-control" placeholder="Category Name">
</td>
</tr>
<tr>
<td>Category</td>
<td>
<select class="form-control" id="parent_id" name="parent_id">
<option value="">Select Category</option>
<?php if(!empty($result)){ ?>
<?php foreach($result as $category){ ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['category_name']; ?></option>
<?php
if(!empty($category['subs'])) {
foreach ($category['subs'] as $sub) {
?>
<option value="<?php echo $category['id'] ?>"><?php echo '--' . $sub['category_name'] ?></option>
<?php
}
}
?>
<?php } }else{
echo '<li>Sorry no category found.</li>';
} ?>
</select>
</td>
</tr>
<tr collspan="2">
<td align="center">
<input type="submit" name="submit" value="submit">
</td>
</tr>
</table>
<input type="hidden" name="id" id="id" value="<?= !empty($editRecord[0]->id)?$editRecord[0]->id:'';?>" >
</form>
</body>
</html>
<script type="text/javascript">
$("#signup_form").validate({
onkeyup: false,
rules:{
category_name: {
required: true
},
},
messages:{
category_name:{
required: "Category Name cannot be blank.",
},
},
});
function isChar(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >=48 && charCode <= 57) {
return false;
}
return true;
}
$('#signup_form').submit(function(e) {
/* Populate data to state dropdown */
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url('Category/insert_record/');?>",
data: form.serialize(),
success:function(data){
//console.log(data);
$('#parent_id').html('<option value="">Select Category</option>');
var dataObj = jQuery.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.id).text(this.category_name);
$('#parent_id').append(option);
});
}
toastr.success('Category Added Successfully.', 'Success Alert', {timeOut: 5000});
$('#signup_form').trigger("reset");
},
error: function() { toastr.danger('Something went worng.', 'Danger Alert', {timeOut: 5000}); }
});
});
</script>
Create a file list.php
<link rel="stylesheet" type="text/css" href="<?=$this->config->item('css_path')?>bootstrap.min.css">
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery-3.2.1.js"></script>
<html>
<body>
<table border="2" align="center">
<tr>
<td width="30">#</td>
<td>Product Name</td>
<td>Price</td>
<td>Category Name</td>
<td>Sub_Category Name</td>
<td>Image</td>
<td>Action</td>
</tr>
<?php
foreach($products as $product)
{
?>
<tr>
<td><?php echo $product->id;?></td>
<td><?php echo $product->product_name;?></td>
<td><?php echo $product->price;?></td>
<td><?php echo $product->category_name;?></td>
<td><?php echo $product->subcategory_name;?></td>
<td><img style="width: 50px;height: 40px;" src="<?php echo base_url('uploads/'. $product->image);?>" /></td>
<td>
Edit
<span class='delete' id='del_<?php echo $product->id; ?>'>Delete</span>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="2">Add new</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
// AJAX Request
$.ajax({
url: "<?php echo base_url('Category/delete/');?>",
type: 'POST',
data: { id:deleteid },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
<style type="text/css">
.panel-heading a{float: right;}
#importFrm{margin-bottom: 20px;display: none;}
#importFrm input[type=file] {display: inline;}
</style>
Now create category_model
class Category_model extends CI_Model
{
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}
public function get_categories()
{
$this->db->select('id,category_name');
$result = $this->db->get('categories');
return $result->result();
}
public function get_category(){
$this->db->select('id,category_name');
$this->db->where('parent_id',0);
$result = $this->db->get('categories');
return $result->result();
}
function getSubs($params = array())
{
$this->db->select('id, category_name,parent_id');
$this->db->from('categories');
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('categories.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
return $result;
}
public function get_products()
{
$this->db->select('products.id,category_name,parent_id,product_name,price,subcategory_name,image');
$this->db->from('categories');
$this->db->join('products','products.category_id = categories.parent_id');
$this->db->join('sub_categories','sub_categories.cat_id = categories.id');
$result=$this->db->get();
return $result->result();
}
public function get_detail($id){
$this->db->select('*');
$this->db->where('id',$id);
$result = $this->db->get('products');
return $result->result();
}
}
?>
Create Category Controller.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('category_model');
$this->load->model('Common_model');
}
public function index()
{
$data['products'] = $this->category_model->get_products();
$this->load->view('category/list',$data);
}
public function add()
{
$data['categories']=$this->db->get('categories')->result_array();
$data['result']=$this->category_model->ordered_menu( $data['categories'],0);
$this->load->view('category/add',$data);
}
public function insert_record()
{
$this->load->library('form_validation');
if($this->input->server('REQUEST_METHOD') == 'POST')
{
$this->form_validation->set_rules('category_name','Category Name','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('category/add');
}
else
{
$post_array = $this->input->post();
if($post_array['parent_id'] == '')
{
$data = array(
'category_name' => $post_array['category_name'],
'parent_id' => 0,
);
}else{
$data = array(
'category_name' => $post_array['category_name'],
'parent_id' => $post_array['parent_id'],
);
}
$inser_data = $this->Common_model->insert('categories',$data);
if(!empty($inser_data))
{
$allcategory = $this->category_model->get_categories();
foreach ($allcategory as $value) {
$cat[] = $value;
}
echo json_encode($cat);
}
}
}
}
public function add_product()
{
$data['categories']=$this->category_model->get_category();
$this->load->view('category/add_product',$data);
}
public function get_subcatries(){
$subcat = array();
$category= $this->input->post('parent_id');
if($category){
$con['conditions'] = array('parent_id'=>$category);
$subcat = $this->category_model->getSubs($con);
}
echo json_encode($subcat);
}
public function insert()
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name']))
{
if (0 < $_FILES['file']['error'])
{
echo 'Error during file upload' . $_FILES['file']['error'];
} else
{
if (file_exists('uploads/' . $_FILES['file']['name']))
{
echo 'File already exists : uploads/' . $_FILES['file']['name'];
}
else
{
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
$photo = $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
$this->load->library('form_validation');
if($this->input->server('REQUEST_METHOD') == 'POST')
{
$this->form_validation->set_rules('product_name','Product Name','trim|required');
$this->form_validation->set_rules('price','Price','trim|required');
$this->form_validation->set_rules('category_id','Category Name','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('category/add');
}
else
{
$post_array = $this->input->post();
if($post_array['subcat_id'] == '')
{
$data = array(
'product_name' => $post_array['product_name'],
'price' => $post_array['price'],
'category_id' => $post_array['category_id'],
'image' => $photo,
'subcat_id' => 0,
);
}else{
$data = array(
'product_name' => $post_array['product_name'],
'price' => $post_array['price'],
'category_id' => $post_array['category_id'],
'image' => $photo,
'subcat_id' => $post_array['subcat_id'],
);
}
$inser_data = $this->Common_model->insert('products',$data);
if(!empty($inser_data))
{
echo '1';
}else{
echo '0';
}
}
}
}
public function edit_record()
{
$id = $this->uri->segment(3);
$result = $this->category_model->get_detail($id);
if(empty($result))
{
redirect('Category/');
}
$data['editRecord'] = $result;
$this->load->view('category/add_product',$data);
}
}
?>
This create for add product with category.
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery-3.2.1.js"></script>
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery.validate.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.css" rel="stylesheet" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?=$this->config->item('css_path')?>bootstrap.min.css">
<html>
<head>
<div id="myDropdown" class="dropdown-content">
Category Form
Product Listing
</div>
<div align="center"><h3>Product Form</h3></div>
</head>
<body>
<form id="product_form" method="post" action="" enctype="multipart/form-data" >
<table border="1" align="center" width="450">
<tr>
<td>Product Name</td>
<td>
<input type="text" id="product_name" name="product_name" onkeypress="return isChar(event)" value="<?php echo !empty($editRecord[0]->product_name) ? $editRecord[0]->product_name :'' ?>" class="form-control" placeholder="Product Name">
</td>
</tr>
<tr>
<td>Price</td>
<td>
<input type="text" id="price" name="price" onkeypress="return isNumber(event)" value="<?php echo !empty($editRecord[0]->price) ? $editRecord[0]->price :'' ?>" class="form-control" placeholder="Price">
</td>
</tr>
<tr>
<td>Category</td>
<td>
<select class="form-control" id="category_id" name="category_id">
<option value="">Select Category</option>
<?php if(!empty($categories)){ ?>
<?php foreach($categories as $category){ ?>
<option value="<?php echo $category->id ?>"><?php echo $category->category_name; ?></option>
<?php } }else{
echo '<li>Sorry no category found.</li>';
} ?>
</select>
</td>
</tr>
<tr>
<td>Sub Category</td>
<td>
<select class="form-control" id="subcat_id" name="subcat_id">
<option value="">Select Sub Category</option>
</select>
</td>
</tr>
<tr>
<td>Image</td>
<td>
<input type="file" name="file" id="file" value="<?php echo !empty($editRecord[0]->file) ? $editRecord[0]->file :'' ?>">
</td>
</tr>
<tr collspan="2">
<td align="center">
<input type="submit" name="submit" value="submit">
</td>
</tr>
</table>
<input type="hidden" name="id" id="id" value="<?= !empty($editRecord[0]->id)?$editRecord[0]->id:'';?>" >
</form>
</body>
</html>
<script type="text/javascript">
$("#product_form").validate({
onkeyup: false,
rules:{
product_name: {
required: true,
},
price: {
required: true,
},
category_id:{
required: true,
}
},
messages:{
product_name:{
required: "Product Name cannot be blank.",
},
price:{
required: "Price cannot be blank.",
},
category_id:{
required: "Category Name cannot be blank.",
}
},
});
function isChar(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >=48 && charCode <= 57) {
return false;
}
return true;
}
function isNumber(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
$(document).ready(function(){
$('#category_id').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'<?php echo base_url('Category/get_subcatries'); ?>',
data:'parent_id='+category_id,
success:function(data){
$('#subcat_id').html('<option value="">Select Subcategory</option>');
var dataObj = $.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.id).text(this.category_name);
$('#subcat_id').append(option);
});
}else{
$('#subcat_id').html('<option value="">Subcategory not available</option>');
}
}
});
}else{
$('#subcat_id').html('<option value="">Select Category first</option>');
}
});
$('#product_form').submit(function(e) {
var id = $('#id').val();
e.preventDefault();
if(id == '')
{
url = "<?php echo base_url('Category/insert/');?>" + $("#id").val();
$.ajax({
url:url,
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
if (data == 1) {
//setTimeout(function(){document.location.href = "index"},500);
toastr.success('Recored Added Successfully.', 'Success Alert', {timeOut: 5000});
}
$('#product_form').trigger("reset");
},
error: function() { alert("Error posting feed."); }
});
}
else
{
url = "<?php echo base_url('Category/update/');?>" + $("#id").val();
$.ajax({
url:url,
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
if (data == 1) {
toastr.success('Recored Updated Successfully.', 'Success Alert', {timeOut: 5000});
setTimeout(function(){document.location.href = "index"},5000);
}
//$('#signup_form').trigger("reset");
},
error: function() { alert("Error posting feed."); }
});
}
});
});
</script>

Categories