live search in html table - php

I want to search by product name then get productdetailsid from db then compare it with each row in this table if it exists , set bachground-color for row!
<div class="input-group m-b"><span class="input-group-btn">
<button type="button" class="btn btn-primary">Go!</button> </span> <input type="text" class="form-control"id="autocomplete">
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align: center">#</th>
<th style="text-align: center">Product Name</th>
<th style="text-align: center">Quantity</th>
<th style="text-align: center">Product Price</th>
<th style="text-align: center">Whole Price</th>
<th style="text-align: center">Supplier Name</th>
<th style="text-align: center"></th>
</tr>
</thead>
<tbody>
<?php
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$sql = "select p.productname,p.quantity,p.onesale,p.wholesale,p.productdetailsid,s.fullname from productdetails p , supplier s where s.supplierid = p.supplierID LIMIT $start_from,$per_page";
$count = ($page*5)-4;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form method=\"post\" action=\"\">";
echo "<tr>";
echo "<td>" . $count++ . "</td>";
echo "<td>" . $row["productname"] . "</td>
<td>" . $row["quantity"] . "</td>
<td>" . $row["onesale"] . "</td>
<td>" . $row["wholesale"] . "</td>
<td>" . $row["fullname"] . "</td>
<td><button type=\"submit\" class=\"btn btn-xs btn-danger\" name=\"removeBtn\"><i class=\"fa fa-times\"></i> </button></td>
<td style=\"display:none;\"><input type=\"hidden\" name=\"id\" value='".$row["productdetailsid"]."'>
</td>"
;
echo "</tr>";
echo "</form>";
}
}
$conn->close();
?>
</tbody>
</table>
</div>

For Live search in the table you need to use AJAX for getting the result, then using that result you can use Javascript loop to find which rows are found and change the color. I would prefer JSON output (JSON array output) from the PHP script, I can use that in Javascript Loop...
in PHP
You need to make a seperate PHP file for getting ajax output...say ajax.php
<?php
//Assuming that 'q' is the POST variable for finding the query
if(!empty($_POST['q']))
{
//Put your database query execution code here with using q as search query
//Set header to JSON
header('Content-Type:application/json');
//assuming that $result is associative array of your SQL query output
which contains array of the rows to be hightlighted
echo json_encode($result);
}
This will give a JSON array output which can be easily read by AJAX or $.post functions...
in Javascript
here's the tricky part. you need to make an ajax call and then use that data to highlight the rows....but first need to give an ID to the table body...
...<tbody id="table1">....</tbody></table>
Then you need to use ajax or $.post function to make the call, I have used $.post as it's simple
/**** Cosidering "input1" is a input element for getting query to be searched with id = input1 ****/
var q_data = $("#input1").val();
$.post(ajax.php,
{
q: q_data
},
function(data,status)
{
$.each($("#table1").find("<tr>"),function(i,value)
{
var element = $(this);
$.each(data,function(i,val2){
if(val2 == $(element).find("<td>").text())
{
$(element).css('background','lgihtyellow');
}
});
});
}
);
The code may not work before suitable changes, but this is the logic and concept of ajax based live search in the table

Related

How can I put a form for each row of a table

Here's the thing, I need to update a selected row from a table, so I'm putting a form for each row of it (Every single row has an update button) and when I click update, it doesn't submit, actually, doesn't do anything.
Here's my code, I'll be grateful with the solution.
<div class="table-responsive">
<table class="table table-condensed">
<thead class="">
<tr>
<th>ID</th>
<th>Project</th>
<th>Type</th>
<th>Kick-Off Date</th>
<th>Deadline Date</th>
<th>Current Ninja</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$q = $_GET['q'];
$sql="SELECT pr.project_name, pr.project_type, pr.project_start_date, pr.project_end_date, us.nombre, st.id_status, pr.id_project FROM NT_Projects as pr LEFT JOIN Project_Status as st on st.id_status = pr.id_status LEFT JOIN NT_Clients as cl on cl.id_client = pr.id_client LEFT JOIN usuarios as us on us.username = pr.username WHERE cl.id_client = $q";
$result = mysql_query($sql) or die(mysql_error());
$upt = 1;
while($row = mysql_fetch_array($result)) {
echo '
<div id="update-project">
<form method="post" action="sistema/_actions/updateProject.php" id="res-update-proj-'.$upt.'">';
$kickoff = date('m/d/Y', strtotime($row[2]));
$deadline = date('m/d/Y', strtotime($row[3]));
echo '<tr>';
echo '<td width="95px">
<input class="form-control" name="id_Proj" type="text" value="'.$row[6].'" readonly>
</td>';
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $kickoff . "</td>";
echo "<td>" . $deadline . "</td>";
echo "<td>" . $row[4] . "</td>";
echo '<td width="225px">';
echo '<select class="form-control" name="proj_Status">';
$qStatus = "SELECT * FROM Project_Status;";
$exStatus = mysql_query($qStatus);
while($rStatus = mysql_fetch_array($exStatus))
{
if($row[5] == $rStatus[0])
echo '<option value="'.$rStatus[0].'" selected>'.$rStatus[1].'</option>';
else
echo '<option value="'.$rStatus[0].'">'.$rStatus[1].'</option>';
}
echo '</select>
</td>
<td class="text-center">
<button type="submit" class="btn btn-sm btn-primary btn-UProj" value="res-update-proj-'.$upt.'">Update</button>
<div id="res-update-proj-'.$upt.'" style="width: 100%; margin:0px; padding:0px;"></div>
</td>
</tr>
</form>
</div>';
$upt = $upt + 1;
}
?>
</tbody>
</table>
</div>
That code is being called from another HTML with ajax
You cannot mix table tags with divs and forms according to the web standards. If you do, browser's HTML-parser will mix your tags in unpredictable way.
The only solution I know is to utilize CSS:
<div style="display: table">
<form style="display: table-row">
<div> style="display: table-cell"></div>
</form>
</div>

Delete MySQL row from PHP while loop

I have a while loop displaying my database columns and rows in table.
I want make a button which can delete specific MySQL row but unfortunately I can't select which of all rows have to be deleted simply because I use "while loop" to display my database content in HTML.
Providing picture for better understanding what I want to do:
So yeah, I want that when the green button is clicked - send MySQL query to delete this row (which is existing in my DB).
Providing code:
<?php
//CONECT TO MYSQL
include 'database.php';
//GET VALUES
$sql = "SELECT * FROM amountcontainer";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
//Table headlines - NOT A PHP
echo "<table class='moneytable'>
<tr>
<th style='background-color: #2d323a; color: white;'>Date</th>
<th style='background-color: #2d323a; color: white;'>Amount</th>
<th style='background-color: #2d323a; color: white;'>Reason</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
//RED //Make statement of amount red if it has a " - "
if(strpos($row['amount'],'-') !== false)
{
echo
"
<tr>
<th style='font-weight: normal;background-color: #ff9999;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-reason'>" . $row['reason'] . "</th>
</tr>
";
}
//NORMAL //Make statement of amount normal if it doesn't have a " - "
else
{
echo
"
<tr>
<th style='font-weight: normal;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;' class='row-reason'>" . $row['reason'] . "</th>
</tr>
";
}
}
echo "</table>";
}
else
{
echo "0 results";
}
First, only use <th> elements for the table headers. For the actual data cells use the <td> element.
To allow deletion of individual database rows you can include links in your table. In your loop that creates the table rows:
<tr>
<td>" . $row['time'] . "</td>
<td>" . $row['amount'] . "</td>
<td>" . $row['reason'] . "</td>
<td><a href='?deleteId=$row[keyID]'>Delete</a></td>
</tr>
In this case, when the "Delete" link is selected it calls your same script with a $_GET variable: "deleteId" which you can test for and if found, perform the delete of the row. You can also embed the table in an html form and add a submit button to a cell in each row, with the value of the submit set to the row id to delete.
This sounds like a place for ajax. Heres a crude example that might give you a good starting point.
<?php
while($row = $result->fetch_assoc()) {
$isNegative = strpos($row['amount'],'-') !== false;
echo "<tr class='record' data-id=\"{$row["id"]}\">";
//Use ternary operator & css classes
echo "<td class='standard-record ".$isNegative ? "color-red" : "" ."''>{$row["record"]}</td>";
echo "</tr>";
}
?>
<script>
$(".record").click(function(){
var request = {
id: $(this).data("id")
};
$.post( "delete-record.php", request, function(data){
$(this).remove();
});
});
</script>
Change this
if(strpos($row['amount'],'-') !== false) # wrong way
to this
if($row['amount'] < 0) # detecting negative numbers
You need to add an extra
<th style='font-weight: normal;' class='row-reason'><a class="crossBtn" href="?del_id=".$row['id']."> </a></th>
And the get the del_id and delete this specific records.

Use data from an SQL query, but don't display column in table

EDIT: If I use $colName instead of $colname, I'd have no issues. Stupid, simple fix.
I have a query pulling 6 columns from multiple tables. The final column is necessary to be used in a dynamic URL I'm generating, but I don't want that column to display on my table. How can I hide it/make it not show up? Is there a way to call the data, but not use it in my table?
Query ex:
SELECT a, b, c, d, e, exTable.f as CID
FROM table exTable
JOIN <other tables>
WHERE stuff happens
Table (you can see that my header row will hide fine, but the content won't):
<table>
<thead>
<tr>
<th class="header"><strong>A</strong></th>
<th class="header"><strong>B</strong></th>
<th class="header"><strong>C</strong></th>
<th class="header"><strong>D</strong></th>
<th class="header"><strong>E</strong></th>
<th class="header" style="display:none"><strong>F</strong></th> <!-- THIS WORKS -->
</tr>
</thead>
<tbody>
<?
foreach($tableData as $row)
{
echo "<tr>";
foreach($tableColNames as $colName)
{
if ($colname=='CID') {
echo "<td style='display:none'>" . $row[$colName] . "</td>"; <!-- THIS DOES NOT -->
}
elseif ($colName=='e') {
echo "<td><a href='http://my.url.here/".$row[CID]."_Document.pdf' target='_blank'>" . $row[$colName] . " </a></td>";
}
else {
echo "<td>" . $row[$colName] . "</td>";
}
}
echo "</tr>";
}
?>
</tbody>
</table>
You have a typo: $colname should be $colName.
if ($colname=='CID') {
Stupid, simple solution: use $colName instead of $colname.

get and display multiple checkbox values from database using php

i having two check boxes when i am selecting both check boxes i want to show the value related to both from database ,but now i able to print only one id of check boxes i want to show both data can anyone help hoe to show both a value ,Below is my code:
html
<input type="submit" name="Update" src="/image/exporttt.png" style="margin:0px;cursor:pointer">
<tbody>
<?php
$clientid=$_GET['clientid'];
if($clientid!=""){
$sql = mysql_query("SELECT * FROM clientnetworkpricehistory");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo '
<td id="CPH_GridView1_clientid" style="width:140px" class=" clientid '.$rows["net_id"].'">'.$rows["clientid"].'</td>
<td id="CPH_GridView1_country" style="width:160px" class=" country '.$rows['net_id'].'">'.$rows["country"].'</td>
<td id="CPH_GridView1_networkname" style="width:156px" class="networkname '.$rows["net_id"].'">'.$rows["networkname"].'</td>
<td id="CPH_GridView1_mccmnc" style="width:250px" class=" mcc'.$rows["net_id"].'">'.$rows["mcc"].'</td>
<td id="CPH_GridView1_mccmnc" style="width:250px" class=" mnc '.$rows["net_id"].'">'.$rows["mnc"].'</td>
<td id="CPH_GridView1_oldprice" style="width:320px" class=" oldprice '.$rows["net_id"].'">'.$rows["pricefrom"].'</td>
<td id="CPH_GridView1_newprice" style="width:129px" class=" newprice '.$rows["net_id"].'">'.$rows["priceto"].'</td>
<td id="CPH_GridView1_oldroute" style="width:143px" class="oldsupplierroute '.$rows["net_id"].'">'.$rows["routefrom"].'</td>
<td id="CPH_GridView1_newroute" style="width:143px" class=" newsupplierroute '.$rows["net_id"].'">'.$rows["routeto"].'</td>
<td id="CPH_GridView1_comments" style="width:143px" class=" comments '.$rows["net_id"].'">'.$rows["status"].'</td>
<td id="CPH_GridView1_from" style="width:143px" class=" fromdate '.$rows["net_id"].'">'.date('d.m.Y H:i', $rows["datetime"]).'</td>
<td style="width:65px" class=" '.$rows["net_id"].'"><input type="checkbox" name="chk1" value=" '.$rows["net_id"].'"/></td>
</tr>';
}
}
?>
</tbody>
jssearch.php
<?php
//connecting to db
$variable=$_POST['chk1'];
foreach ($variable as $variablename)
{
$sql_select="SELECT * from clientnetworkpricehistory where net_id=$variablename";
$queryRes = mysql_query($sql_select);
print"$sql_select";
}
echo "<table border='1'>
<tr>
<th>country</th>
<th>networkname </th>
<th>mcc</th>
<th>mnc</th>
<th>datetime </th>
</tr>";
while($row = mysql_fetch_array($queryRes))
{
echo "<tr>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['networkname'] . "</td>";
echo "<td>" . $row['mcc'] . "</td>";
echo "<td>" . $row['mnc'] . "</td>";
echo "<td>" . $row['datetime'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
my out put was(i am checked two checkboxes and i am trying to print two check boxes id it only showing one can any one help me how to do that)
56
Warning: Invalid argument supplied for foreach()
Use name="chk1[]" in your HTML so the checkboxes will be posted as an array.
Besides that:
The mysql_* functions are deprecated, consider using mysqli_* or PDO
You are vulnarable to SQL-injection on your where net_id=$variablename"
I agree with Peter but you also might wanna fix this little typo:
'.$rows['net_id'].'">'.$rows["country"].'
That's line 2 of that large echo you have with all the <td>s. The $rows['net_id'] should be double quotes.
But you knew that...:)

How can I pass the chosen value on a modal-box to PHP?

I've the code to initialize the modal-box:
<script>
var grid_modal_options = {
height: 'auto',
width: '80%',
modal: true
};
function showProductsModalBox() {
$("#products_modal_box").dialog(grid_modal_options);
$("#products_modal_box").parent().appendTo('form:first');
}
</script>
<div id="products_modal_box" title="Products" style="display: none;">
<div class="in">
<div class="grid-12-12">
<form id="products_modal_box_form" action="#" method="post">
<table>
<thead>
<tr>
<th> </th>
<th>Product</th>
</tr>
</thead>
<!-- Query for read mysql goes here (I skipped this line because it's not the main thing I'm gonna ask since it's run well) /-->
<tbody>
<?php
//read the results
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a href='#'>Choose</a></td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
And:
<input type='text' id='products_id_textbox' name='products_id_textbox' />
<a href='#' onclick='showProductsModalBox(); return false;'>Choose products</a>
The code succeeds to show the modal box. But how to return the "Product" chosen by the user to the textbox "products_id_textbox"? Thanks.
add inline javascript:
<?php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td>Choose</td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
Instead using inline JS, you can write so (or something like this);
// php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a rel='dialog' data-id='{$fetch[0]}'>Choose</a></td>";
print " <td>{$fetch[0]}</td>";
print "</tr>";
}
// js
$(document).ready(function(){
...
$("a[rel=dialog]").each(function(){
var id = this.getAttribute("data-id");
$('#products_id_textbox').val(id);
$('#products_modal_box').dialog('close');
});

Categories