I have a list that is populated from a database table as below.
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo
$row['AnalysisID']; ?>">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[]" value="<?php echo $row["Unit"]; ?>">
</td>
<td><?php echo $row['Site']; ?></td>
<td><?php echo $row['Unit']; ?></td>
</tr>
<?php
}
?>
This displays the data perfectly, and in inspect all data is correct.
However I want to be able to check the various check-boxes and insert those rows to another table.
to achieve this I am using:
$counter = count($_POST["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["Site"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$x]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
The problem is it doesn't matter what rows I check it always inserts the first in the list, it inserts the correct number just from the start of the list.
For example if I check the last 4 in the list I get the first 3.
Any pointers would be a great help.
Checkbox values are only sent if the checkboxes are checked, so the index will be different in the $_POST["name"] and the other $_POST arrays.
(Unchecked checkbox inputs are seen as "unsuccessful" https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.2 )
Try adding the ID as index instead, then selected data will keep together.
(I renamed the name array to aid to better match the contents)
<td>
<input type="checkbox" name="aid[<?php echo $row['AnalysisID']; ?>]" value="1">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Unit"]; ?>">
</td>
Then looping through the post data with foreach(). Only the checked ID's will be posted so no need for if (!empty() check.
if (isset($_POST["aid"])) { // to avoid php undefined notice if none selected
foreach ($_POST["aid"] as $id=>$value){ // the index is what we need, using $id
$PI_NO = mysql_real_escape_string($id);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["Site"][$id]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$id]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
Also I strongly advice you to change from using deprecated mysql_* functions, use mysqli or PDO instead. Why shouldn't I use mysql_* functions in PHP?
Related
I use foreach to show data came from database.
This is for Plan_data
<?php foreach ($veddingPlanData as $row) { ?>
<input box with value containing "echo row->value_name" >
<?php } ?>
This is for task data as check box [here I want to show the checkbox list in which the task is given to plan_id they appear as cheeked checkbox and remaining list with not checked status)
<?php foreach ($veddingPlanTaskMappingData as $row) { ?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked><?php echo $row->task_name?><br>
<?php } ?>
Here I show the whole task list in check box.
<?php foreach ($allVedingTasks as $row) { ?>
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name?><br>
<?php } ?>
I want to foreach the task_name list with selected some task as there mapped plan_id.
Finally I found It
<?php
$arrSelVedTask = array();
foreach ($veddingPlanTaskMappingData as $row) {
$arrSelVedTask[$row->task_id] = '';
}
?>
<div class="form-group">
<lable for="task_id" class="control-label col-sm-12">Plan Task LIST:</lable>
<div class="col-sm-10">
<div class="checkbox" style="margin-left:40px;">
<?php foreach ($allVedingTasks as $row) {
if(isset($arrSelVedTask[$row->task_id])) {
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked ><?php echo $row->task_name; ?><br><?php
}
else{
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name; ?><br><?php
}
}
?>
Simply add a check:
<?php
foreach ($veddingPlanTaskMappingData as $row) {
$checked = ($row->task_id == YOUR_CONDITION) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" <?php echo $checked?>><?php echo $row->task_name?><br>
<?php } ?>
Use set_checkbox Of CI
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" <?php echo set_checkbox('task_id', $row->task_id); ?> ><?php echo $row->task_name?>
at first in your model fetch the value of checkbox which is in your database then call that function in controller and pass the value to view page. then use if statement with every checkbox item to check whether the value is same or not. and write echo "checked";command if the condition match.
First of all we will take all the categories than we are taking an Id and using it for showing the checked list from the database. First we select the table values based on Id than we will fetch the record. We are having the data in the database column using , comma like 1,2,3,5,9. Than we save it in array and at last we just show that array to the page.
$table="select * from categorytable";
$this->result=mysqli_query($this->con,$table);
$this->count=mysqli_num_rows($this->result);
if($this->count < 1)
{
return "<div class='form-group'>".$messages->getResponseMessage("No category is added.", "Warning")."</div>";
}
else
{
$alert='';
$select="select Category from table where Id='$id'";
$result= mysqli_query($this->con, $select);
$amrow= mysqli_fetch_array($result);
$getAminity=$amrow["Category"];
$getArray= explode(",",$getAminity);
while($row= mysqli_fetch_array($this->result))
{
if(in_array($row[Id],$getArray)){
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' checked name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
else
{
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
}
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.
First of all my apopoliges , this may b a possible duplicate question, I searched and found few answered but they are not very helpfull in my case.
I have the follwing form with static and dynamic values
<input type="hidden" value="<?php echo $Quote ?>" id="amount" name="amount"/>
<input type="hidden" value="<?php echo $NoDays?>" id="total_days" name="total_days"/>
<?php $sql = mysql_query("select * from tbloffers ORDER BY Sequence"); ?>
<?php while($rows = mysql_fetch_array($sql)) { ?>
<input type="hidden" value="<?php echo $rows['Id']; ?>" name="offerid[]" />
<input type="hidden" value="<?php echo $rows['Name']; ?>" name="offername[]" />
<input type="hidden" value="<?php echo $rows['Price']; ?>" name="offercharges[]" />
<?php } ?>
<input type="email" id="customeremail" name="customeremail" required/>
And my save.php file is
$date = date("j M, Y");
$total_days = mysql_real_escape_string($_POST["total_days"]);
$amount = mysql_real_escape_string($_POST["amount"]);
$customeremail = mysql_real_escape_string($_POST["customeremail"]);
$offerid = $_POST["offerid"];
$offername = $_POST["offername"];
$offercharges = $_POST["offercharges"];
when I hit Submit I would like to be able to have all those values inserted into database through a loop. I tried foreach and struggled.
Note: The static values will repeat with dynamic values.
e.g $date, $amount will remain same on Insertion.
$sql = "INSERT INTO table < What comes next?
Thanks in advance.
You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($offerid as $i => $offer) {
$offer = mysql_real_escape_string($offer);
$name = mysql_real_escape_string($offername[$i]);
$charges = mysql_real_escape_string($offercharges[$i]);
mysql_query("INSERT INTO table (date, total_days, amount, customer_email, offerid, offername, offfercharges)
VALUES ('$date', '$total_days', '$amount', '$customeremail', '$offer', '$name', $charges')");
}
P.S. You really should stop using the mysql extension and upgrade to mysqli or PDO, so you can use prepared queries instead of string substitution.
I have a db table called 'ice_flavours' with the columns: 'id', 'flavours', 'date', 'selected'.
and another table called 'ice_today' like: 'id', 'flavours', 'date', 'selected'.
Now, on the left of the page I want to call from 'ice_flavours' and print the entries in a form together with a checkbox.
On the right of the page it shall say SHOWCASE where I want the todays selected flavours to be shown and they shall just stay in there until the end of today´s date and then automatically be discarded. Also when they were selected to show in SHOWCASE, i want them to not show on the left side.
So, when I select the checkbox next to a flavour, the values 'id', 'flavours', 'date', 'selected' ought to be entered into 'ice_today' but for some reason just always the last row of the ice_flavours table is entered and i get the message "Duplicate entry '0' for key 'PRIMARY'"
Maybe this can all be done by just using a single db table but I havent figured it yet. Can someone help please
edit.php:
<?php ob_start();
include_once("dbinfo.inc.php");
include_once("config.php");
if(isset($_POST['submit'])){
$selected = $_POST['selected'];
$id = $_POST['id'];
$flavour = $_POST['flavour'];
$date = $_POST['date'];
if($_POST["submit"] == "submit") {
for($i=0;$i<sizeof($selected);$i++) {
if(!empty($flavour)) {
echo"";
echo "<pre>";
print_r($_POST);
echo "</pre>";
$query="INSERT INTO ice_today VALUES('$id','$flavour','$date','$selected[$i]')";
mysql_query($query) or die(mysql_error());
}
}
echo "Entry added";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Edit</title>
</head>
<body>
<form name="form1" id="form1" method="POST" action="edit.php">
<table border="1" width="200px">
<td>
<table border="1" width="200px">
<?php
$result = mysql_query("SELECT * FROM ice_flavours WHERE ('selected' != '1') ORDER BY flavour ASC");
$results = mysql_num_rows($result);
if ($results > 0)
{
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
$id=mysql_result($result,$i,"id");
$flavour=mysql_result($result,$i,"flavour");
?>
<tr>
<td align="center" valign="middle">
<?php echo $flavour; ?>
<input type="text" name="id" id="id" value="<?php echo $id; ?>">
<input type="text" name="flavour" id="flavour" value="<?php echo $flavour; ?>">
<input type="text" name="datum" id="datum" value="<?php echo date('Y-m-d'); ?>">
<input type="checkbox" name="selected[]" id="selected" value="<?php echo '1'; ?>">
</td></tr>
<?php
$i++;
}
?>
<input type="submit" value="submit">
<?php } ?>
</td>
<td>
<table border="1" width="200px">
<tr><td align="center" valign="middle">
SHOWCASE
</td></tr>
<?php
include_once("dbinfo.inc.php");
include_once("config.php");
$result2 = mysql_query("SELECT * FROM ice_today ORDER BY flavour ASC");
$results2 = mysql_num_rows($result2);
if ($results2 > 0)
{
$num2=mysql_numrows($result2);
$j=0;
while ($j < $num2)
{
$id=mysql_result($result2,$j,"id");
$flavour=mysql_result($result2,$j,"flavour");
?>
<tr><td align="center" valign="middle">
<?php echo $flavour; ?>
</td></tr>
<?php
$j++;
}
}
echo '</td></tr></table>';
?>
</body>
</html>
<?php ob_end_flush(); ?>
Please take a look at the MySQL Reference Manual. You need to specify each column in your INSERT statement:
$query="INSERT INTO ice_today(id, flavours, date, selected) VALUES('$id','$flavour','$date','$selected[$i]')";
I also suggest you to not use the original MySQL-extension anymore, as it is deprecated as of PHP 5.5.x. When using another MySQL extension (MySQLi or PDO for instance: mysqli or PDO - what are the pros and cons?) you can also use prepared statements to become safe against SQL injections (which you aren't right now).
POST-values can be manipulated and as you just feed them into your query via string concatenation, you're not safe against them.
If the field for ID is an autoincrement field, you need to leave it off the insert because the db server will determine the value itself. You should list the fields being inserted, and leave that one off:
$query="INSERT INTO ice_today (flavours, date, selected) VALUES('$flavour','$date','$selected[$i]')";
Listing the fields you are inserting to also prevents insert statements from breaking when you add new fields later. So its good practice to start now.
There are lots of issues in your code.
You text boxes having same name with different values if there are two flavors.
Therefore flavor or id will be always from last row.
You can do something like this.
1.Replace your text boxes with this,
<input type="text" name="id_<?php echo $id; ?>" value="<?php echo $id; ?>">
<input type="text" name="flavour_<?php echo $id; ?>" value="<?php echo $flavour; ?>">
<input type="text" name="datum_<?php echo $id; ?>" value="<?php echo date('Y-m-d'); ?>">
<input type="checkbox" name="selected[]" value="<?php echo $id; ?>">
2.Replace your top if block (i.e. after submit)
if (isset($_POST['submit']) && $_POST["submit"] == "submit") {
$selected = $_POST['selected'];
for($i=0; $i < sizeof($selected); $i++) {
$id = $selected[$i];
$flavour = $_POST['flavour_' . $id];
$date = $_POST['date_' . $id];
$query="INSERT INTO ice_today VALUES('$id','$flavour','$date','$id')";
mysql_query($query) or die(mysql_error());
}
}
my code works as expected but a little issue occurred, i try retrieving values from checkboxes with same name and hidden fields with the same name, it works but one of the hidden field keeps on returning the first value even if the checkbox was not selected.
here is my code
while($row=mysql_fetch_array($res1)){
?>
<tr><td class='bold'><?php echo $sn;?><input type="hidden" name="snum[]" value="<?php echo $sn; ?>" /></td>
<td><?php echo $row['subLocationName']; ?>
<input type="hidden" name="location[]" value="<?php echo $row['dllink_id']; ?>"/></td>
<td><input type="checkbox" name="available[]" value="<?php echo $row['subLocationName']; ?>"/></td>
<input type="hidden" name="locationID[]" value="<?php echo $row['locationName']; ?>"/>
<input type="hidden" name="sublocation[]" value="<?php echo $row['subLocationName']; ?>"/>
<input type="hidden" name="device[]" value="<?php echo $row['deviceName']; ?>"/>
<td></td><td></td></tr>
<?php
$sn++;
}
the values are from my database.
the retrieving code is this
if(isset($_POST['submit_btn'])){
$serial_num = $_POST['snum'];
$locationDeviceLink = $_POST['location'];
$linkAvailable =$_POST['available'];
$location = $_POST['locationID'];
$subLocation = $_POST['sublocation'];
$device = $_POST['device'];
$measure_date = date("Y-m-d");
$sn = count($linkAvailable);
for ($i=0; $i<$sn; $i++ ){
if(!empty($linkAvailable[$i])){
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}
}
the problem is the subLocation value, it keeps returning the first value then the second as it appears even if the associated checkbox is not checked and another checkbox is checked, please can anyone help me out, cant't think of anything more.
thanks in advance
joseph O
Rather then testing for !empty try using php's function isset.
for ($i=0; $i<$sn; $i++ ){
if(isset($linkAvailable[$i])) {
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}