I am trying to insert multiple rows to a database table if check box is selected. But in my code when I am trying to insert, new rows are inserting based on check box selection. But no data is passing. I need some advice on below code to modify:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$qry="select * from pi";
$result=mysql_query($qry);
?>
<form action="check.php" method="post">
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
echo "<tr><td><input type=checkbox name=name[] value='".$row['id']."'>".$row['PI_NO']."</td><td>".$row['CUSTOMER_NAME']."</td><td>".$row['PI_ADDRESS']."</td></tr>";
}
?>
<input type="submit" value="save" id="submit">
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$name=$_POST['name'];
foreach($_POST['name'] as $x)
{
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
?>
Notes:
You forgot to bind the name of your checkbox using a single tick (')
You used variables in your query which you didn't defined and assigned value with yet
You only passed on the value of name, and did not include the Pi Address and Customer name. I'll be passing them by hidden input using <input type="hidden">.
I'll change the way you check your passed on form by looping them and check them using for() and if()
Use mysql_real_escape_string() before using them in your queries to prevent some of the SQL injections. But better if you consider using mysqli prepared statement rather than the deprecated mysql_*.
Is your post a single file? If it is, you must enclose your query using an isset() to prevent error upon loading the page.
You didn't close your <form>
Here's your corrected while loop:
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo $row['id']; ?>">
<?php echo $row["PI_NO"]; ?>
<!-- HERE IS THE START OF YOUR TWO HIDDEN INPUT -->
<input type="hidden" name="piaddress[]" value="<?php echo $row["PI_ADDRESS"]; ?>">
<input type="hidden" name="customer[]" value="<?php echo $row["CUSTOMER_NAME"]; ?>">
</td>
<td><?php echo $row['CUSTOMER_NAME']; ?></td>
<td><?php echo $row['PI_ADDRESS']; ?></td>
</tr>
<?php
} /* END OF WHILE LOOP */
?>
<input type="submit" value="save" id="submit">
</form> <!-- YOU DID NOT CLOSE YOUR FORM IN YOUR POST -->
And your query:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$counter = count($_POST["name"]); /* COUNT THE PASSED ON NAME */
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["customer"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["piaddress"][$x]);
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
} /* END OF CHECKING THE CHECKBOX IF SELECTED */
} /* END OF FOR LOOP */
?>
Lots of little problems. And some big ones.
as $x){ .. $x is not being used so I assume you just loop for the number of checked boxes.
These have no values: '$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS'
Missing </form>
Not being used: $name=$_POST['name'];
<?php
echo '<form action="check.php" method="post"><table><tr><th>A</th><th>B</th><th>C</th></tr>';
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$sql = "select `id`,`PI_NO`, `CUSTOMER_NAME` ,`PI_ADDRESS` from `pi`";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo "<tr><td><input type=\"checkbox\" name=\"name[]\" value=/"$row[0]/"'>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo '<input type="submit" value="save" id="submit"></form>';
foreach($_POST['name'] as $x){
$sql="INSERT INTO pi (`PI_NO`, `CUSTOMER_NAME`, `PI_ADDRESS`)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($sql);
}
?>
Related
I have set up an update query which will update values entered into text fields on a while loop.Then for some reason only the last row data in the loop will be updated and the rest will stay the same.i know the issue .cause the the last attribute row overwrite the other in form so when update update only the last row
code
<?php
include'../config/connect.php';
$id = $_SESSION['agent'];
$sql = "Select * from nps where agent_id = '$id'";
$result = $cont->query($sql);
if ( $result->num_rows > 0 ){
?>
<form action="update.php" method="post">
<?php
while($row = $result->fetch_assoc()){
?>
<tr>
<td> <?php echo $row['date']; ?> </td>
<td> <?php echo $row['phone']; ?> </td>
<td> <?php echo $row['survey_date']; ?> </td>
<td> <input type="hidden" name="id" value="<?php echo $row['agent_id']; ?>"> <?php echo $row['agent_id']; ?> </td>
<td> <?php echo $row['agent_name']; ?> </td>
<td> <?php echo $row['nps_rating']; ?> </td>
<td> <?php echo $row['sats']; ?> </td>
<td> <?php echo $row['agent_satisfaction']; ?> </td>
<td> <?php echo $row['ir']; ?></td>
<td><textarea name="comment" ><?php echo $row['comment']; ?></textarea></td>
</tr>
<?php
}
};
?>
</table>
<div><input type="submit" name="submit" > </div>
</form>
update.php file
<?php
session_start();
include'../config/connect.php';
$comment = $_POST['comment'];
$id = $_POST['id'];
if($_POST['submit']){
$sql = "UPDATE nps SET comment='$comment' WHERE id='$id' ";
};
if ($cont->query($sql) === true){
echo 'done';
}else{
echo 'notdone';
}
?>
First of all, you have two input names: id and comment. Once submitted, the form will be processed from start to finish, meaning the values that are actually processed in your PHP will be the last ones.
You will want to make these unique, and since you’re ID is hidden, it is less important. My suggestion would be to dynamically create names, such as comment_{id} and than in your PHP with the query to update, you go through all of your $_POST values, replace out the comment_ from the key, and execute a query to update the values.
You are also open to SQL injection and should take steps to prevent that.
You must have have inputs with unique names. I suggest to make a input name from row’s ID and attribute name, as for e.g. comment will be like ‘1-comment’. Then in the update script you need to iterate over the data and make the update query for each data. Cheers.
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>
<?php
include("dbFunctions.php");
$query ="SELECT * FROM `physical_examination` WHERE `PE_Opt_ans`= 0";//select form options name
$result = mysqli_query($link,$query);
?>
<div id="tabs-3">
<table>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="tab0">
<?php while ($arrayResult = mysqli_fetch_array($result)){ ?>
<tr>
<td><label for="input"><b><?php echo $arrayResult['PE_Opt_name']?></label></td>
<?php if ($arrayResult['PE_Opt_type'] == "textarea") { ?>
<td><textarea rows="8" cols="45"name = "other1"></textarea></td>
<?php } else { ?>
<td><input type="<?php echo $arrayResult['PE_Opt_type']?>" name="input<?php echo $arrayResult['id']?> " ></td>
</tr>
<?php } ?>
<?php } ?>
<br> <input value="Submit" type="submit" name="submit1">
</form>
</table>
<?php
include "dbFunctions.php";
if(isset($_POST['submit1'])) {
$number = $_POST['other1'];
I am stuck here.
How do I $_POST the form based on the while loop after I click on submit button? Do I need another while loop again for the name value of input <?php echo $arrayResult['id']?>
I didn't quiet get what you want but i assume you want the contents of the textarea generated by the while loop.
Change in your loop the names from input to input[] and other1 to other1[]
If you var_dump($_POST) afterwards you should see that they are now an array which you can loop over with foreach
PS: You should NEVER EVER eat raw $_POST/$_GET inputs and PHP_SELF is another security breach. But that's just my two cents
I have a HTML table that displays all my table entries. Also in the table is a delete button next to every SQL entry.
I want to be able to delete an entry the user selects. I've made the form to Post PHP_Self, and I'm passing in the index $i from the while loop as a reference:
$i = 0;
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type='hidden' name='remove_entrie_ID' value='<? echo $i; ?>' />
<input type='submit' value='Delete' name='remove_entrie'>
</form>
</td>
</tr>
<?
$i++;
}
So this is passed to itself, I now want to do a DELETE WHERE 'INDEX OF TABLE' == $i, type thing? I don't even know if this is possible.
if(isset($_POST['remove_entrie'])){
$index = $_POST['remove_entrie_ID']
echo "Index: " . $index;
//mysqli_query($con, "DELETE FROM Users WHERE INDEX = '$index'");
}
I'm basically using the $i to pick out the index of how the table was loaded, and then using that to pick out which row I want to delete. But I have a feeling this can't be done?
I basically want to delete a row the user has selected from the table.
You don't need $i variable. Just make simple modification in your list:
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="" method="post">
<input type="hidden" name="remove_entrie_ID" value="<? echo $row['uniqueIdentifier']; ?>" />
<input type="submit" value="Delete" name="remove_entrie">
</form>
</td>
</tr>
<?
}
It is also good idea to escape specials chars etc in your post variable to avoid sql injection.
im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");