Here Is my problem: I do not get any error with my code but my problem is when i click the 'Delete Multiple' Button it does nothing not even reload the page.
Note: By The Way the redirect_to(); function i created so do not get confused by thinking that is a php function or anything
PHP Code:
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = $_POST['checkdelete'];
$sql = "DELETE FROM cmarkers WHERE id = " . $mul;
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
HTML Code:
<form action="elerts.php" method="post">
<table class="table table-striped">
<tr>
<td> </td>
<td>Date</td>
<td>Comment</td>
<td>Actions</td>
</tr>
<?php
$sql = "SELECT * FROM cmarkers";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><input type="checkbox" name="checkdelete[]" value="<?php echo $row['id']; ?>" /></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['comment']; ?></td>
<td>DeleteEdit</td>
</tr>
<?php
}
?>
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
Thank You
If you need more info please let me know
First, your code contain some attention and placements errors.
input between <table> outer of td's is incorrect.
You can't make a multiple delete if you generate one form by value to
delete.
Fix them.
Getting Array of muldelete
To all the checked inputs, you must add the array field symbol
to clusterize the name "muldelete" to a post array.
<td><input type="checkbox" name="checkdelete[]" value="<?php $row['id']; ?>" /></td>
PHP side
Now you can fetch whole deletion array, like this:
if(!empty($_POST["muldelete"]))
{
$mul = join(',', $_POST['checkdelete']);
// Using IN() to make only one query for all records instead of multiple
// ex: IN(3, 4, 54, 8)
$query = "DELETE FROM cmarkers WHERE id IN(".$mul.")";
$result = mysqli_query($db, $query);
redirect_to("elerts.php");
}
Security
If ID's are integer value, you can prevent string injection into the sql query
$mul = array_map(function($id)
{
return intval($id);
}, $mul);
Your button is outside the <form></form> tags, so it is not related to the form elements or the form method at all. Instead of having a different form for each checkbox you should surround the entire table with the form tags thus ensuring that all the checkboxes and the button are in the same form.
<form method='post' action='elerts.php'>
<table class="table table-striped">
...all your table data including checkboxes...
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
I think because You are closing form tag earlier than submit button.
Try to put whole table into and should work.
PHP should looks like
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = implode(',',$_POST['checkdelete']);
$sql = "DELETE FROM cmarkers WHERE id IN(" . $mul.")";
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
Related
Dear Stack Overflow members,
I’m trying to create a form for school awards where a user will select a class (level) and submit. The awards for that class (there can be many awards) will display in a table with a dropdown of a list of students in that class beside each award.
The user will then select a student from the dropdown beside each award and submit again which will save the records in a table.
It is working fine except the last part where the students and the awards are not being saved. Not sure if the issue is with one isset within another isset is causing the issue.
<?php
if(isset($_POST['submit'])) {
include 'db_connect.php';
$level = $_POST['level'];
$query = mysqli_query($conn, "SELECT a.awardcode, a.level, b.awardname, a.year FROM awardyrlevel AS a
INNER JOIN award AS b
ON a.awardcode = b.awardcode
WHERE a.level = '$level' AND a.year = year(curdate())");
?>
<table border="1" style= "background-color: white; color: #761a9b; <!--margin: 0 auto-->;" >
<thead>
<tr>
<th>Award Code</th>
<th>Award Name</th>
<th>Year Level</th>
<th>Select Student</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $query ) ){
?>
<tr>
<td> <input type = "text" name="awardcode[]" value = "<?php echo $row['awardcode']; ?>" readonly /> </td>
<td><?php echo "{$row['awardname']}" ?> </td>
<td><?php echo "{$row['level']}" ?></td>
<td><select name="studcode[]" >
<option disabled selected value> -- Select Student -- </option>
<?php
$sql = mysqli_query($conn, "SELECT * FROM student where year_level = '$level'");
while ($row = mysqli_fetch_assoc($sql)){
echo '<option value = " '.$row['stud_code'].'"> '.$row['name'].' </option>';
}
?>
</select>
</td>
</tr>\n;
<?php } ?>
</tbody>
</table>
<br><br>
<input id="save_button" type="submit" name="saveselection" value="Save Selection">
<input id="exit_button" type="submit" name="exit" value="Exit" onclick="window.history.go(-1); return false;">
<?php
if(isset($_POST['saveselection'])) {
$awardcode = $_POST['awardcode'];
$studcode = $_POST['studcode'];
$level = $row['level'];
$year = year(curdate());
$session_user = '2365';
echo $awardcode;
foreach ($_POST['awardcode'] as $awardcode) {
$query = mysqli_query($conn, "INSERT INTO `awardwinner`(`awardcode`, `stud_code`, `level`, `year`, `doe`, `enteredby`)
VALUES ('$awardcode', '$studcode', '$level', '$year', now(), '$session_user')");
}
}
}
?>
The code I have written is simple with html and php. I tried to debug this for quite sometime. Can any of you please suggest what is wrong with this that the records cant be saved?
There are a couple of things wrong with this code, including not keeping to standards of PHP programming. Keep your issets at the top of the page, don't litter them throughout, it makes things difficult to track.
You have an input with the name listed as an array... why? You're not submitting multiple values here. Perhaps you mean to use it as a checkbox/radio? Otherwise it's not needed.
Then in your final query, you're actually using ` for a number of them, instead of ' . That's a ` which should be under your esc key, instead of an apostrophe (')
Also just as a preference, I tend to write for readability rather than raw efficiency when working with a few people, so I personally would write:
$query = "WHATEVER MY QUERY IS";
$get_thing_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($get_thing_query)){
//Do your stuff, if you're not expecting multiple rows don't use while.
}
code:
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<form method="post" name="myform">
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
<?php
}
?>
</table>
</form>
In this code I want to update table enquires2 with unique id. In following image you see that table row having save button this is only one row similarly it have multiple row which having save button in each row. Now I want that when I click on save button of particular row only that row data will be update. How can I fix this problem ? Please help.
Thank You
You could use AJAX and jQuery to do this and send the data to a separate PHP file and assigning the $row['ID'] to a data-value attribute of the button,
$("#save-btn").click(function(){
id = $(this).attr(data-value);
***** rest of values here
$.ajax({
method: "GET",
data: {id: id, rest of: data here},
url: phpfile.php,
success: function(){
console.log("Success");
}
})
});
While in the PHP file you would take get the id like,
$_GET['id'], and same with the other values since we are using the GET method and then put them in the update query.
First of all, for security reason you need to change this query to a prepared statement see PHP MySQLI Prevent SQL Injection:
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
This line is bad anyway, you are missing a opening quote for $comment2.
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
Are you sure $link is an actual mysqli link?
As for the html part, you need to mkae one form for each record. See the link posted HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
alternatively you could do something bad like only adding the $id to evry field for every row (similar to:)
<input type ='submit' name='save[<?=$id;?>]' id='save' value='Save' />
and in the php code check witch key is set.
if(isset($_POST['save']) && is_array($_POST['save'])){
$id=key($_POST['save']);
}
You will need to replicate the bad thing for your comments as well but as a proof of concept you can run this snippet on phpfiddle.org
<?php
print_r($_POST);
if(isset($_POST['save']) && is_array($_POST['save'])){
echo key($_POST['save']);
}
?>
<html>
<form method='post'>
<input type='submit' name='save[1]' value='1' />
<input type='submit' name='save[2]' value='2' />
</form>
</html>
Wish i could provide you a really full answer but there's alot of work to be done on your code for it to be 'proper coding'. Again this becaome a matter of opinion beside the fact that your code is vunerable to sql injection and is NOT accepable.
Don't use your code at all for security vulnerability. Read more about sql injection Here. After all, For each row () create a form with a hidden input storing id of row .
I revised my code to make it work,create a nested table inside your td, so that tag will be accepted,
also see this link for a working reference,
HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr><td><table>
<form method="post" name="myform">
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
</form>
</table>
</td>
</tr>
<?php
}
?>
</table>
My main issue that I am running into is basically this:
I have a while loop that generates results from a query. With the results that have been generated, I want the ability to update the table the original query was from.
The query produces the expected results, but the table is not being updated when I click the REMOVE button. I am also trying to find a solution for the results to be updated after the UPDATE query executes...
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'><input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/></td>
</tr>";
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='{$row['vin']}'";
mysql_query($removeSql) or die('check that code dummy');
}
}
mysql_close($connection);
?>
That's a submit button, will not work without form tag. You can't do it this way.
You can write the remove code on a separate page and convert that submit button to normal button and pass vin id on click of that button and call that page using ajax.
Or if you don't know ajax and want to do it on that page itself then do it this way :
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>
<form action="" method="POST">
<input type="hidden" name="vin_id" value="<?php echo $row['vin']; ?>">
<input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/>
</form></td>
</tr>";
}
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='".$_POST['vin_id']."'";
mysql_query($removeSql) or die('check that code dummy');
}
mysql_close($connection);
?>
I have an HTML form with some records contained in it. The records should be deleted by selecting one or all records corresponding checkbox.
When I select a record's checkbox and click delete, the query runs successfully, but record does not delete.
Here is the PHP code:
if(isset($_POST['delete']))
{
$allCheckBoxId = $_POST['chkDel'];
array_map ('mysql_real_escape_string', $allCheckBoxId);
$ids = implode(",", $allCheckBoxId);
$object=new connection();
$object=$object->dbConnect();
$st=$object->prepare(
"delete * from banners where bannerid IN (?)");
$st->bindParam(1, $ids);
$delete=$st;
$delete->execute();
if($delete)
{
echo "record deleted successfully." .
"This will go to banners within 5 sec";
}
else
{
echo "not deleted";
}
}
And HTML form:
<form name="myform" action="listbanners.php" method="post" OnSubmit="return onDelete();" id="frm1">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="13"><input type="checkbox" class="checkbox" title="select all" onclick="checkAll(document.myform.chkDel);" name="CheckAll" /></th>
<th width="13">ID</th>
<th>Name</th>
<th><input type="submit" name="delete" value"Delete"></th>
</tr>
<?php
$object=new connection();
$object=$object->dbConnect();
$st=$object->prepare("select * from banners order by bannerid desc");
$st->execute();
while($row=$st->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><input name="chkDel[]" type="checkbox" title="select" class="checkbox" value="<?php echo $row['bannerid'];?>"/></td>
<td><?php echo $row['bannerid'];?></td>
<td><h3 onClick="location='editbanner.php?bannerid=<?php echo $row['bannerid'];?>'"><?php echo $row['file'];?></h3></td>
<td><input type="submit" name="delete" value="delete"/></td>
</tr>
</form>
$st=$object->prepare("delete * from banners where bannerid IN (?)");
$st->bindParam(1, $ids);
You're trying to bind a single parameter to an array of values. You need to pass in each value as a separate parameter; for example:
$st=$object->prepare("delete * from banners where bannerid IN (?,?,?)");
You need to include a placeholder for each value you want to include in your IN clause. You can generate the SQL dynamically, based on how many items are in $ids.
I missed the 'DELETE *', which is invalid syntax; but I'm leaving this in place because the point I did notice is valid. This is an incomplete answer, not a wrong one.
my current problem is :
I have a HTML table created "dynamically" according to how many rows brings back a mysql_query. The first column gets tha data from the query and the second column have a text field (see below):
<?php
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours" id="hours" value="0"/></td>
</tr>
<?php } ?>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
After my table is "ready", I want to fill in my text fields and insert these values in an sql table. What I don't know is how I can get the value of each column through the id I set, sth like
if(isset($_POST['complete'])){
for($i=0; $i<$rcnt; $i++){
//INSERT INTO APARTMENT (idAPARTMENT, HOURS) VALUES ($a, **table.row.id**)
}
}
Can someone help? Is this possible to be done?
Thanks in advance!
He, thing you have to do is add $rid as name to text box, then just submit form and you will have them in $_POST["row"+$rid];
You can loop through every $_POST and if variable starts with row + num save it in db
foreach($_POST as $key => $value)
//if $key starts with row execute your db save
I hope this helps
Put that table into a form with method=POST and when submitting you'll find all input's in the $_POST array by name.
<?php
print_r($_POST);//this will just show you the contents of the array, you play with it later on
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<form action="" method="POST"><!-- table must be included in a form with action pointing the script location, "" means itself -->
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours<?= $a ?>" id="hours" value="0"/></td><!-- name="hourse<?= $a ?>" each name must be unique, that's why you include the ID from your table. It's not a good idea to put a counter, use actual data from the table. -->
</tr>
<?php } ?>
</table>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
</form>
The post "get data from dynamically created html table for certain columns" was very useful. It helped me a lot, but needs a little change:
<?php
//database connectivity
mysql_connect ("localhost","root","","sis")or die("cannot connect");
mysql_select_db("sis")or die("cannot select DB");
//query to fetch data
$sql1="select * from student";
$result1= mysql_query($sql1);
// forming table to view data
if($result1){
echo "<table cellspacing='1' cellpadding='5'>
<th width='30%'>Roll_No </th>
<th width='40%'>Name </th>
<th width='30%'>Sem & Sec </th>";
while($row=mysql_fetch_array($result1)){
$Roll_No=$row['Roll_No'];
$Name=$row['Name'];
$Sem_Sec=$row['Sem_Sec'];
echo"<tr>
<td>$Roll_No</td>
<td>$Name</td>
<td>$Sem_Sec</td>
</tr>";
}
?>