i am trying to delete one row from a table based on the selection of the user:
<form method="post" action="updatecart.php">
<td> <button class="btn" type="submit" name="update" >Update</button></td>
<td> <button class="btn" type="submit" name="remove" >Remove</button></td>
<input type="hidden" name="itemid[]" value=<?php echo"$row[3]"?>>
<input type="hidden" name="cartid[]" value=<?php echo"$row[6]"?>>
<td><img alt="" src="/photos/<?php echo"$row[4]"?> " width= 100 height=100></td>
<td><?php echo"$row[0]"?></td>
<td><input type="number" id="quantity" name="quantity[]" min=1 max=<?php echo"$row[5]"?> value=<?php
echo"$row[1]"?>></td>
<td><?php echo"$row[2]"?></td>
<?php $total = $total * $row[1]?>
<td><?php echo"$total"?></td>
</tr>
<?php $totaloftotal+=$total; ?>
whenever the use presses the remove button only the selected item, but what happens is everything gets deleted.
this is the
elseif(isset($remove)){
for($z= 0; $z <count($itemid); $z++ ){
try{
require('connection.php');
$cartid= $_POST["cartid"];
$itemid= $_POST["itemid"];
$qty= $_POST["quantity"];
$sql2= "delete from cart where qty=$qty[$z] and iid=$itemid[$z] and cart_id=$cartid[$z] and uid=$uid";
$x = $db->exec($sql2);
the update works just fine, i only have a problem with the delete.. help.
Perhaps the following might give you an idea of how you might proceed. The PHP that processes the POST request has been designed to work with Prepared Statements but is not yet complete and I will stress that this is not tested!
Please look through the html and read the comments which hopefully explain what is going on at that point. Obviously the content of the table ( ie: each table row and cells etc ) will be dynamically generated by db query results - below is static for demo.
The pseudo db processing code here uses mysqli but it looks like you are using PDO so use that as a guide only... look at Prepared Statements here
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<!--
using a single form to process multiple records requires
a little more consideration than for a single record.
Submitting the form "as-is" leaves you with no way to know
which particular record PHP should update because they are
all suitable candidates potentially.
One method I made reference to was to use a single form with
just the fields required for processing that are populated
by javascript. To that end...
* Assign a name to the form for easy identification.
* remove the `[]` from field names in the form.
* remove the two hidden fields and assign `dataset` attributes to each button
The table below is a loose facsimile of what I deduced the
original table to look like...more or less.
-->
<form method='post' name='update' action='updatecart.php'>
<table>
<tr>
<th>Update</th>
<th>Remove</th>
<th>Image & Link</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td><button class="btn" type="button" name="update" data-cartid="23" data-itemid="1">Update</button></td>
<td><button class="btn" type="button" name="remove" data-cartid="23" data-itemid="1">Remove</button></td>
<td><img alt="" src="/photos/banana.jpg" width=100 height=100 /></td>
<td>Senga-X</td>
<td><input type="number" name="quantity" min=1 max=74 value=17 /></td>
<td>43</td>
<td>93</td>
</tr>
<tr>
<td><button class="btn" type="button" name="update" data-cartid="69" data-itemid="1">Update</button></td>
<td><button class="btn" type="button" name="remove" data-cartid="69" data-itemid="1">Remove</button></td>
<td><img alt="" src="/photos/apple.jpg" width=100 height=100 /></td>
<td>Senga-Y</td>
<td><input type="number" name="quantity" min=1 max=45 value=10 /></td>
<td>35</td>
<td>1505</td>
</tr>
</table>
<!--
use only the number of hidden elements as are
needed in the sql later for update/delete
-->
<input type='hidden' name='cartid' />
<input type='hidden' name='itemid' />
<input type='hidden' name='qty' />
<input type='hidden' name='task' />
</form>
<script>
document.querySelectorAll('button[name="update"],button[name="remove"]').forEach( bttn=>{
bttn.addEventListener('click',function(e){
// stop the form from being submitted conventionally
e.preventDefault();
// obtain reference to the form
let form=document.forms.update;
// set values of hidden elements based upon the particular button that was clicked
form.cartid.value=this.dataset.cartid;
form.itemid.value=this.dataset.itemid;
form.qty.value=this.parentNode.parentNode.querySelector('input[name="quantity"]').value;
form.task.value=this.name;
// send your form with only these values!
form.submit();
});
});
</script>
</body>
</html>
And the PHP to process the request:
<?php
#updatecart.php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['itemid'], $_POST['cartid'], $_POST['qty'], $_POST['task'] ) ){
$cartid=$_POST['cartid'];
$itemid=$_POST['itemid'];
$qty=$_POST['qty'];
$task=$_POST['task'];
switch($task){
case 'remove':
$sql='delete from cart where cart_id=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$cartid);
break;
case 'update':
$sql='update cart set qty=? where cart_id=?';
$stmt=$db->prepare($sql);
$stmr->bind_param('ss',$qty,$cartid);
break;
}
#etc etc etc
exit();
}
?>
Related
I'm working on a multifield form to register issues, but when submitting the data to the mysql db it misplaces the checkmark values. The first submition gets the 1 values, the rest get 0 and the following error message:
Warning: Undefined array key 1 in
C:\xampp\htdocs\panel_gastos\v1.3\ingreso_problemas.php on line 97**
the screen looks like this:
And here is the result of the submission in mySQL: the first element should have had "recurrente=1" and "resuelto=0"
And the code is the following:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport", content="width=device-width, initial-scale=1.0">
<title>Portal gastos - ingreso de problemas</title>
<!---Bootstrap-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>
<!---JQuery-->
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<!---aƱadir filas--->
<script type="text/javascript">
$(document).ready(function(){
var html = '
<tr>
<td>
<input class="form-control" type="text" name="Prob[]" required="">
</td>
<td><!---<input type="hidden" name="Recurrente[]" value="0"/>--->
<input class="primary" type="checkbox" name="Recurrente[]" value="1">
</td>
<td>
<input class="form-control" type="text" name="KPI[]" >
</td>
<td>
<input type="date" name="Fecha[]" required="">
</td>
<td>
<input type="hidden" name="Solucionado" value="0">
<input type="checkbox" name="Solucionado[]" value="1">
</td>
<td>
<input class="btn btn-danger" type="button" name="remove" id="remove" value="remove">
</td>
</tr>';
var max = 15;
var x = 1;
$('#add').click(function(){
if(x < max){
$("#table-field").append(html);
x++;
}
});
$('#table-field').on('click','#remove' ,function(){
$(this).closest('tr').remove();
x--;
});
});
</script>
</head>
<body>
<div class="container">
<form class="insert-form" id="insertform" method="post" action="">
<hr>
<h1 class="text-center">input field</h1>
<hr>
<div class="input-field">
<table class="table table-bordered" id="table-field">
<!---encabezados--->
<tr>
<th>Prob</th>
<th>Rec</th>
<th>KPI</th>
<th>fecha suceso</th>
<th>solucionado</th>
<th>add/remove</th>
</tr>
<!---enviar data--->
<?php
$bdd= new PDO("mysql:host=localhost;dbname=test_usuarios; charset=utf8mb4", "root", "");
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
if (isset($_POST['save'])){
$createtime = date('Y-d-m');
$usr = $_SESSION["username"];
$ceco = $_SESSION['ceco'];
$problema = $_POST['Prob'];
$recurrente = $_POST['Recurrente'];
$kpi_sol = $_POST['KPI'];
$fecha_sol = $_POST['Fecha'];
$solucionado = $_POST['Solucionado'];
foreach($problema as $key=>$value){
$save= <<<SQL
INSERT INTO incidentes_cecos(fecha_creacion, usr, ceco, problema, recurrente, KPI_sol, fecha_evento, resuelto)
VALUES('$createtime','$usr', '$ceco','$value','$recurrente[$key]','$kpi_sol[$key]','$fecha_sol[$key]','$solucionado[$key]');
SQL;
$query = $bdd->query($save);
};
}
?>
<!---campos--->
<tr>
<td><input class="form-control" type="text" name="Prob[]" required=""></td>
<td><!---<input type="hidden" name="Recurrente[]" value="0"/>---><input class="primary" type="checkbox" name="Recurrente[]" value="1"></td>
<td><input class="form-control" type="text" name="KPI[]" ></td>
<td><input type="date" name="Fecha[]" required=""></td>
<td><input type="hidden" name="Solucionado" value="0"><input type="checkbox" name="Solucionado[]" value="1"></td>
<td><input class="btn btn-warning" type="button" name="add" id="add" value="add"></td>
</tr>
</table>
<center>
<input class="btn btn-success" type="submit" name="save" id="add" value="save data">
</center>
</div>
</form>
</div>
</body>
</html>
So far i've tried some solutions to send 1 if the checkbox is selected and 0 if not. I'm not sure what is happening, most probably this is bad use of arrays from my part.
<input type="hidden" name="Solucionado[]" value="0">
<input type="checkbox" name="Solucionado[]" value="1">
Even if the name of the hidden field was fixed so that it matches that of the checkbox - you can not use this solution, when you have multiple checkboxes with the same name.
If you had
<input type="hidden" name="Foobar" value="0">
<input type="checkbox" name="Foobar" value="1">
then this solution works - because PHP overwrites parameters with the same name, so $_POST['Foobar'] would contain the 0 the hidden field submits, if the checkbox was not checked, and 1 if it was (because then both 0 and 1 get submitted under the same name, and the later 1 overwrites the earlier 0.)
But if you have fields with [] in the name, PHP will not overwrite, but create an array with all the submitted values. That is the behavior that you want for your text fields of course - but it prevents this checkbox workaround from working.
Because, if you had the above hidden input plus checkbox say, three times, but you check only one of the checkboxes - then that still results in four values being submitted: The three hidden inputs all submit their 0, and the one checked checkbox submits its 1. So once again, you will not be able to correctly correlate that to your text field values.
The only viable solution here is that you explicitly specify the index the value should get in the resulting array, upfront. Your first text input would be named name="Prob[0]", and the checkbox name="Solucionado[0]". And with [1] on the next set of fields, and so on. The hidden field gets completely removed.
Since you are dynamically appending the form fields using JavaScript, you will need to modify that part to keep a counter, and modify the output in the relevant places accordingly.
Then you can loop over $_POST['Prob'], and then for each entry check if one with the same index exists in $_POST['Solucionado'].
But since you need to make modifications in how you create the form to begin with, it might make more sense to change the field names to something like name="data[0][Prob]" and name="data[0][Solucionado]". Then you get all the data in $_POST['data'] organized by numeric index first, and then you have Prob, Solucionado, etc. below that - with the Solucionado still only existing if the respective checkbox was checked. But the data is grouped more logical to begin with.
I would like click on submit and the value input in the field to be stored in database.
However, I do not want to use a form action. Is it possible to do it without creating form action with PHP?
<tr>
<form method="post">
<tr>
<td>
<label for="Item name"><b>Finish Product:</b></label>
</td>
<td>
<input id="finish_product" type="text" maxlength="100" style="width:100px"name="finish_product" required>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Save" id="submit" />
</td>
</tr>
<?php
if(isset($_POST['submit']))
{
var_dump($_POST); exit;
$SQL = "INSERT INTO bom (finish_product) VALUES ('$finish_product')";
$result = mysql_query($SQL);
}?>
</tr>
Use Jquery ajax to do this. Try this:
HTML
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<body>
<table>
<tr>
<td><label for="Item name"><b>Finish Product:</b></label></td>
<td><input id="finish_product" type="text" maxlength="100" style="width:100px" name="finish_product" required></td>
</tr>
</table>
<input type="button" value="Save" id="submit" />
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.ajax({
url: '1.php',
data: {finish_product: $('#finish_product').val()},
success: function (result) {
alert(result)
}
});
});
});
</script>
</body>
PHP
(1.php)
Note: Use mysqli_query since mysql_query is depricated in latest versions. And use bind param instead of directly appending values to query.
<?php
if (!empty($_GET)) {
$SQL = "INSERT INTO bom (finish_product) VALUES ('".$_GET['finish_product:']."')";
$result = mysql_query($SQL);
echo 1;
} else {
echo -1;
}
?>
This isn't a form, this is just a series of table elements with various inputs and a submit button. Clean up the code - there's no closing tr tag, and where is the submit button supposed to be?
Add a form element around it.
You need an method attribute to the form - in this case, "post". Without the action attribute, it will default to the same page.
<!-- add form tag -->
<form method="post">
<tr>
<td>
<label for="Item name"><b>Finish Product:</b></label>
</td>
<td>
<input id="finish_product" type="text" maxlength="100" style="width:100px"name="finish_product" required>
</td>
</tr>
<!-- added new row for submit button - you might want to have the td element span two columns? -->
<tr>
<td>
<input type="submit" value="Save" id="submit" />
</td>
</tr>
</form>
<-- end of form -->
<?php
if(isset($_POST['submit']))
{
//see what is being POSTED - comment out this line when you're happy with the code!
var_dump($_POST); exit;
$SQL = "INSERT INTO bom (finish_product) VALUES ('$finish_product')";
$result = mysql_query($SQL);
}
I fetch SQL data with a while loop and insert the data into a table. With a form and a submit button i can save modified values.
My simplified code:
<table>
<tr>
<?php
//SQL QUERY
//...
while ($row = mysql_fetch_array($sql_header)) {
$var_ab = $row['ab'];
$var_id = $row['id'];
?>
<form id="form1" action="" method="POST">
<td>
<input type="text" value="<?php echo $var_ab; ?>"
</td>
<td>
<input type="text" value="<?php echo $var_id; ?>"
</td>
//PLACEHOLDER FOR SECOND FORM
<?php
}
?>
</tr>
<td>
<input type="submit" name="save" value="SAVE" class="classsubmit" />
</td>
</form>
</tr>
</table>
So far, so good. So, how can I insert a second form to delete an entry? I've tried to place this code (PLACEHOLDER FOR SECOND FORM - see above)
<td>
<form id="form2" action="" method="POST">
<input type="text" value="<?php echo $var_id;?>"
</form>
</td>
but it's not working and it's not allowed to nest forms.
Any suggestions?
If you only want to delete an entry on the page or in the database you could try a button or a span with an onclick function.
for example:
<span onclick="window.location='?delete=<?php echo $row[(unique-value-in-database-from-this-row)]; ?>'; return false">Delete entry</span>
Make sure you add return false or the first form will be submitted. If you use a button make sure it has type="button"
On this page could be a PHP code like this:
if(isset($_GET['delete']))
{
$item = $_GET['delete'];
//SQL connect
$result = mysql_query($conection ,"DELETE FROM table WHERE uniquevalue='$item'");
}
I hope gives an idea for a solution.
Please help me out of this.....
I am designing a table which is inside a form.
the table is generated based on while loop.
In each row there is a download button.
when i click download the POST value should get the same row information.
But my POST variable is giving me the last row information only.
I tried using input-type as hidden... But it did not work
Here is the code for your reference
enter code here
<form name="simpleform" method="post" action="insert.php">
<?php
$data = "environment";
$user_name = $_SESSION['username'];
$serch = mysql_query("SELECT * FROM data WHERE (data_category = '" . $data . "') ");
while ($record=mysql_fetch_assoc($serch))
{?>
<tr class="warning">
<td >
<input type="text" value=<?php echo $record['data_ID'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_ID'];?> name="dataid" />
</td>
<td >
<input type="text" value=<?php echo $record['data_name'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_name'];?> name="dataname" />
</td>
<td >
<input type="text" value=<?php echo $record['data_downloads'];?> readonly="readonly">
<input type="hidden" value=<?php echo $record['data_downloads'];?> name="datadown" />
</td>
<td >
<input type="text" value="" >
<input type="hidden" value="" name="datause" />
</td>
<td>
<input type="submit" name="simplesubmit" value="Go to download" />
</td>
</tr>
<?php }
exit;
?>
</tbody>
</form>
The problem is that you are using the same name attribute for all your controls. Thus, when PHP receives the form, they get overwritten, and you only see the last value of the form.
The simplest way to avoid that is just appending [] to the end of your names -- eg name=dataid[]. This will make PHP take all arguments as an array, so you don't lose data.
The second problem, is that your submit button also has the same name - you should diversify it by using some row-specific data in its name, such as 'name="submit-'.$record['data_name'].'"'
For more info, more code from you is needed, such as what are the data you are printing like.
Every post button can have its name and value, so if you change your code to produce a traceable post button name you can just do whatever you want with that.
<table>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[1]" value="OK" />
</tr>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[2]" value="OK" />
</tr>
</table>
When the form is posted its very easy to capture which button is clicked;
if ($_POST["submit"]) {
$id = key($_POST["submit"]);
}
Thanks for info... and good response. As you said , i replaced the same and saw the post value is giving me all arguments as array. My purpose is to let the client download file that he clicks. so if the client click the first row button in the table, the post value should get only that Data_name. So that i can run a query to get the URL of that data_name and download
I've made the form below. Is it possible to make it that when user enters the number of fields, for example 6, that the table below has 6 rows. It would be great if it would be possible to make it without any submit button (so that the trigger for this action is exiting from the text input box).
Here is the html code of this form:
<fieldset>
<legend>Student Information</legend>
Number of fields: <input type="text"><br />
Total number of characters: <input type="text">
<br>
<br>
<table border="1">
<th></th>
<th>field</th>
<th>number of characters</th>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
</fieldset>
If this is not possible (without submit button), than in which way would you accomplish the same result? Thank you for any help and/or suggestions.
PHP is server side, it runs only once, when the page is loading. HTML is not a programming language. You could generate the table with PHP, but only if you had a submit button that reloaded the page. If it has to happen because of a user event, it always needs to be done with Javascript.
That means, you will need Javascript to make this work without reloading the page. Ideally, you would use Jquery (Javascript's most popular plugin) to manipulate the DOM.
If you had this input :
<input id="field" type="text">
You could call the on-leave event like this :
$("p").focusout(function()
{
// Delete the previous table, and create a new one, here
});
As for creating the actual table, it isn't complicated, but it is a bit of work. You should read the following reference to start you up :
http://www.tutorialspoint.com/jquery/jquery-dom.htm
You will need to "install" JQuery before-hand, you can simple insert this at the top of your code :
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Okay here is the post only script you require
<?php
$rows=2;
if(isset($_POST['submit']))
{
if($_POST['submit']=='Update')
{
if(isset($_POST['rows'])) $rows=max($rows, intval($_POST['rows'])); // minimum 2 rows
}
else
{
// process posted data here
// reset post or jump to another page
$_POST=array();
//header("Location:index.php");
//exit();
}
}
?>
<form method="post">
<fieldset>
<legend>Student Information</legend>
Number of fields: <input type="text" name="rows" value="<?php echo $rows; ?>"><br />
Total number of characters: <input type="text">
<input type="submit" name="submit" value="Update"/>
<br>
<br>
<table border="1">
<th></th>
<th>field</th>
<th>number of characters</th>
<?php
for($loop=1;$loop<=$rows;$loop++)
{
echo '<tr>';
echo '<td>'.$loop.'</td>';
echo '<td><input name="field['.$loop.']" value="'.$_POST['field'][$loop].'" /></td>';
echo '<td><input name="chars['.$loop.']" value="'.$_POST['chars'][$loop].'" /></td>';
echo '</tr>';
}
?>
</table>
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
It will default to 2 rows (minimum), and retain the data when you update the rows.
If the rows get reduced, then the end ones disappear
It certainly would be doable with just PHP.
So for example, if you typed in '6' rows you could catch the form post and do something like (template form for within the HTML):
<?php for($i=0; $<=$_POST['rows'];$i++): ?>
<!-- This being your whatever html for the table -->
<tr><td></td></tr>
<?php endfor; ?>