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.
Related
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
My goal is to have the items in $row['status'] to change to red if value is OFF and green if value is ON. Any help would be greatly appreciated.
<?php
include("connection.php");
$r = mysqli_query($dbc, "SELECT * FROM enclosure ORDER BY computer ASC");
echo "<table id='table' align='center' border='1' cellspacing='3' cellpadding='3' width='75%'>
<tr>
<td align='left'><b>Enclosure Name</b></td>
<td align='left'><b>Screen Status</b></td>
<td align='left'><b>Time Screen in status</b>
</td><td align='left'><b>Temperature of Enclosure</b></td>
</td><td align='left'><b>Incoming Voltage</b></td>
</tr>";
while($row = mysqli_fetch_array($r)){
$row['voltage'] = $row['voltage'] /1000;
echo "<tr>
<td align='left'>".$row['computer']."</td>
<td align='left'>".$row['status']."</td>
<td align='left'>".gmdate("H:i:s",$row['length'])."</td>
<td align='left'>".$row['temp']."</td>
<td align='left'>".$row['voltage']."</td>
</tr>";
}
mysqli_close($dbc);
$page = $_SERVER['PHP_SELF'];
$sec = "5";
?>
DevlishOne's answer is correct, however you should also consider setting the class of the <td> rather than the color. If you're formatting desires become more sophisticated than red/green (e.g. transitions) or if this is or become a larger chunk of code you will appreciate having the styles shifted out to a css file. It's generally considered a good idea.
ADDITION:
You asked for a simple version using classes:
echo "<td align='left' class='STATUS" . $row['status'] . "'>" . $row['status'] . "</td>";
This uses classes named STATUSON and STATUSOFF so you could use a css stylesheet with
STATUSON {
color: green;
}
STATUSOFF {
color: red;
}
Obviously, you can add more formatting to each of those classes if that's helpful.
Change:
<td align='left'>".$row['status']."</td>
To:
echo "<td align='left' style='color:" . ($row['status'] == "OFF" ? "red" : "green") . "'>" . $row['status'] . "</td>";
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.
I have a script written to grab a row from my database based on current session user, which outputs the row correctly, however I want to insert a small image to be displayed alongside of the echo'd row, and cannot figure out the proper syntax.
if ($row['lifetime']!="")
echo "<div style ='font:12px Arial;color:#2F6054'> Lifetime Member: </div> ".$row['lifetime'];
else
echo '';
?>
basically I want the image to appear right before or after the .$row appears, either or.
You can try:
<?php
if ($row['lifetime'] !== "") {
echo "<div style ='font:12px Arial;color:#2F6054'> Lifetime Member: </div>";
echo $row['lifetime'];
echo "<img src='' alt='' style='width:100px'/>";
}
?>
Just put the HTML for the image into the string you're echoing:
echo "<div style ='font:12px Arial;color:#2F6054'><img src="fill in URL here"> Lifetime Member: </div> ".$row['lifetime'];
You can try as below example
HTML
<table>
<thead>
<tr>
<th>No.</th>
<th>Customer Name</th>
<th>Photo</th>
<th ></th>
</tr>
</thead>
<tbody>
<?php
$tst=0;
$result = mysql_query("select * from acc_cust");
while($row = mysql_fetch_array($result))
{
echo "<tr class='odd gradeX'>";
echo "<td width=5%'>" . $row['ent_no']. "</td>";
echo "<td>" . $row['cust_name']. "</td>";
echo "<td><img src='[path]" . $row['cust_img'] . "' /></td>";
}
?>
</tbody>
</table>
I have a script which returns 5 columns from a php result. I am trying to match one of the columns due date against the current date. If the date returned is older I want to highlight that row. It does not seem to for some reason. I have tested my if statement and it work.
<?php
// First of all initialise the user and check for permissions
require_once "/var/www/users/user.php";
$user = new CHUser(7);
// Initialise the template
require_once "/var/www/template/template.php";
$template = new CHTemplate();
// And create a cid object
require_once "/var/www/WIPProgress/DisplayWIPOnLocation.php";
$WIPProgress= new CHWIPProgress();
$content = "<h1>Check WIP Status on Location </h1>";
$content =
"<form action='index.php' method='get' name ='location'>
<select id='location' name ='location' >
<option>Skin Room</option>
<option>Clicking</option>
<option>Kettering</option>
<option>Closing</option>
<option>Rushden</option>
<option>Assembly</option>
<option>Lasting</option>
<option>Making</option>
<option>Finishing</option>
<option>Shoe Room</option>
</select>
<input type='submit' />
</form>";
if(isset($_GET['location'])) {
$wip = $WIPProgress->ListWIPOnLocation($_GET['location']);
$location = $_GET['location'];
$todays_date = date("Y-m-d H:i:s");
// Now show the details
$content .=
"<h2>Details for $location </h2>
<table>
<tr>
<th>PPDescription</th>
<th>Works Order</th>
<th>Bundle Number</th>
<th>Bundle Reference</th>
<th>Due Date</th>
</tr>";
foreach($wip as $x) {
if(strtotime($x['DueDate']) > strtotime($todays_date)){
$content .=
"<tr bgcolor='#FF0000'>
<td>" . $x['Description'] . "</td>
<td>" . $x['WorksOrder'] . "</td>
<td>" . $x['Number'] . "</td>
<td>" . $x['Reference'] . "</td>
<td>" . $x['DueDate'] . "</td>
</tr>";
}
}
}
else {
$content .= "<h3>Please choose a location to view WIP</h3>";
}
$template->SetTag("content", $content);
echo $template->Display();
?>
Is there any classes available in php which highlights rows returned?
Instead of defining bgcolor with tr define with each td in it.
OR better way to associate a CSS class to the tr and target all the td of this tr through CSS.
$content .= "<tr class='highlight'>...";
<style>
.highlight td
{
background-color:#FF0000;
}
</style>