How to Delete from Loop Multiple Checkbox in PHP - php

I want to delete record from checkbox. I have a form to display data from database like this
$connect = mysqli_connect('Ian', 'root', '', 'penduduk');
$call_db = mysqli_query($koneksi, "select * from tabel_data_penduduk");
<form action="deleteData.php" method="post">
<table style="border:black solid; width: 100%">
<tr style="font-weight: bold">
<th style="width: 2%"><input type="checkbox"/></th>
<th style="width: 3%">No. Identity</th>
<th style="width: 4%">No. Driving License</th>
<th style="width: 10%">Name</th>
<th style="width: 12%">Birth Date</th>
<th style="width: 9%">City Code</th>
</tr>
<?php
$counter=0;
while($db = mysqli_fetch_array($call_db, MYSQLI_NUM)){
echo "<tr>"
. "<td style='text-align:center; width:2%'>"
. "<input type='checkbox' name='deleteNetizen[$counter]' value='". $db[0] ."'/>"
. "</td>"
. "<td style='width: 3%'>". $db[0]. "</td>"
. "<td style='width: 4%'>". $db[1]. "</td>"
. "<td style='width: 10%'>". $db[2]. "</td>"
. "<td style='width: 12%'>". $db[3]. "</td>"
. "<td style='width: 9%'>". $db[4]. "</td></tr>";
++$counter;
}
?>
</table>
<button type="submit" name="btnNetizen" value='ButtonNetizen'>Delete Data Netizen Table</button>
</form>
`
and then the deleteData.php (which is same file as the form) is:
<?php
$netizenData= $_POST['deleteNetizen'];
echo "$netizenData";
$hapusPenduduk = $_POST['btnNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
if($hapusPenduduk){
$deleteData_Netizen = mysqli_query($db, "delete from table_data_netizen where No_Identity = $netizenData");
}
?>
The $netizenData return a value when i debug it, but somehow it can't be deleted from database. I wonder where did i go wrong?
Thanks for help

It's hard to debug completely from this code snippet, but here are some tips for improving / debugging:
Use bind variables instead of strings in your queries. So change your last code snippet to something like:
<?php
$netizenData= $_POST['deleteNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
$delete_stmt = mysqli_prepare($db, "delete from table_data_netizen where No_Identity = ?"); // note that you can / should re-use this prepared statement
if($hapusPenduduk){
mysqli_stmt_bind_param($delete_stmt, $netizenData);
mysqli_stmt_execute($delete_stmt);
// some debug info:
printf("%d rows deleted.", mysqli_affected_rows($delete_stmt));
}
// if necessary
mysqli_stmt_close($delete_stmt);
?>
This change will make it clearer what's happening in your code. For example, if someone put a quote in $netizenData, you'd get weird results. (This is, in fact, where SQL injection attacks come from and why your code is unsafe.) And then you should start to be able to debug things like: did you make it into your if block? Did any rows get deleted? Etc.
Another thing to look at is whether you are committing / need to commit your data. For example, see http://php.net/manual/en/mysqli.autocommit.php for info on autocommit. If it's off (and you're using transactional tables), then you may need to manually commit (or set autocommit to true).
Hope that helps.

It works now. I change the code to:
Form:
<?php
$connect = mysqli_connect('Ian', 'root', '', 'netizen');
$call_db = mysqli_query($connect, "select * from tabel_data_penduduk");
?>
<form action="deleteData.php" method="post">
<table style="border:black solid; width: 100%">
<tr style="font-weight: bold">
<th style="width: 2%"><input type="checkbox"/></th>
<th style="width: 3%">No. Identity</th>
<th style="width: 4%">No. Driving License</th>
<th style="width: 10%">Name</th>
<th style="width: 12%">Birth Date</th>
<th style="width: 9%">City Code</th>
</tr>
<?php
$counter=0;
while($db = mysqli_fetch_array($call_db, MYSQLI_ASSOC)){
echo "<tr>"
. "<td style='text-align:center; width:2%'>"
. "<input type='checkbox' name='deleteNetizen[$counter]' value='". $db['No_Identity'] ."'/>"
. "</td>"
. "<td style='width: 3%'>". $db['No_Identity']. "</td>"
. "<td style='width: 4%'>". $db['No_Driving_License']. "</td>"
. "<td style='width: 10%'>". $db['Name']. "</td>"
. "<td style='width: 12%'>". $db['BOD']. "</td>"
. "<td style='width: 9%'>". $db['City_Code']. "</td></tr>";
++$counter;
}
?>
</table>
<input type="submit" name="btnNetizen" value='Delete Data Netizen Table'/>
</form>
deleteData.php:
<?php
$netizenData= $_POST['deleteNetizen'];
$hapusPenduduk = $_POST['btnNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
if($hapusPenduduk){
$delete_stmt = mysqli_prepare($db, "delete from table_data_netizen where No_Identity = ?");
foreach ($netizenData as $del) {//array processed using foreach
mysqli_stmt_bind_param($delete_stmt, 's', $del);
//'s' is type of parameter $del which is string
mysqli_stmt_execute($delete_stmt);
}
}
?>

Related

count the rows in a table and change the width of a single column ..?

i need to get the counting of the table rows in order as a column in column "N"
also i need to make the column"N" width looks smaller than others columns
i think i have done everything but this is the only point i couldn't achieved
the output should be as the picture :
i hope you could help me guys, thank you
here is my codes :
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// DataBase connection
$host = "localhost";
$user = "root";
$password = "";
$db = "worksheet9";
$con = mysqli_connect($host, $user, $password, $db);
//verfiy Connection
if( mysqli_connect_errno()) {
echo " Connection Error:" . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
$task=$_POST['task'];
// insert sql query
$sql = "INSERT INTO dolist (task) VALUES ('$task')";
$result=mysqli_query($con, $sql);
// verify query
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
<form method='POST'>
<input type="text" name="task" id="task" required
placeholder="add task" oninvalid="this.setCustomValidity('you must fill the task')"
oninput="this.setCustomValidity('')">
<input type="submit"name="submit"value="add task" ><!-- comment -->
</form>
<table border="1">
<tr>
<th> N </th>
<th>ID </th>
<th>task</th>
<th>delete</th><!-- comment -->
<th>update</th>
</tr>
<?php
// Select sql query
$sql = "SELECT ID,task FROM dolist";
$result = mysqli_query($con, $sql);
while ($rows = mysqli_fetch_array($result)) {
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . "<input type='number' readonly name='number' value='" . $rows[''] . "'></td>";
echo "<td>" . "<input type='text' readonly name='id' value='" . $rows['ID'] . "'></td>";
echo "<td>" . "<input type='text' name='task' value= '" . $rows['task'] . "'></td>";
echo "<td>" . "<input type='submit' name='delete' value='x'>" . "</td>";
echo "<td>" . "<input type='submit' name='update' value='update'>" . "</td>";
echo "</tr>";
echo "</form>";
}
if(isset($_POST['update'])) {
$sql = "UPDATE dolist SET task='$_POST[task]'WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "updated";
} else {
echo "update faild";
}
}
//perform only when the user click on Delete
if(isset($_POST['delete'])) {
$sql = "DELETE FROM dolist WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "DELETED";
}else{
echo "delete faild";
}
}
?>
</table>
</body>
</html>
For row numbering add a counter to your PHP code:
$rowNumber = 1;
while ($rows = mysqli_fetch_array($result)){
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . $rowNumber++. "</td>";
// echo other fields...
echo"</tr>";
For formatting, give your table an ID (not essential but it makes the CSS styling more specific)
This should then generate HTML like this:
<table id="results">
<tr><th>N</th><th>ID</th><th>task</th><th>Delete</th><th>Update</th></tr>
<tr><td>1</td><td>11</td><td>task</td><td>X</td><td>Update</td></tr>
<tr><td>2</td><td>12</td><td>task</td><td>X</td><td>Update</td></tr>
</table>
Now you can style it with CSS:
/* Border around the table */
#results {
border: 1px solid grey;
}
/* Border around the individual cells */
#results th, #results td {
border: 1px solid gray;
}
/* Set the width of the first TH. Also sets the width of the res of the column */
#results th:first-of-type {
width:1em;
}
/* Set the width of the 3rd column (the 'task' column */
#results th:nth-of-type(3) {
width:10em;
}
Output:
Note: you could do this by adding class attributes to the <th> elements and styling those. It makes for easier maintenance later.
Use of formatting attributes in HTML tags (like BORDER="1") is considered bad practice and should be avoided.
Don't use JS or PHP to count something pure CSS can help you with
Use CSS Counters
Use <thead> and <tbody> table elements
Use width: 0%; for the td you want really condensed in width
.tbodyCount {
counter-reset: rowIndex;
}
.tbodyCount tr {
counter-increment: rowIndex;
}
.tbodyCount td:nth-child(1)::before {
width: 0%; /* Make as smaller as possible */
content: counter(rowIndex); /* Learn about counters*/
}
<table>
<thead>
<tr>
<th>N</th>
<th>ID</th>
</tr>
</thead>
<tbody class="tbodyCount">
<tr>
<td></td>
<td>Foo</td>
</tr>
<tr>
<td></td>
<td>Bar</td>
</tr>
<tr>
<td></td>
<td>Baz</td>
</tr>
</tbody>
</table>

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>

live search in html table

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

Changing color of item in table depending on data value

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>";

How to echo html and row from database

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>

Categories