PHP Array Variable Being Passed Incorrectly - php

I have a query which is doing something strange. This checkbox is in a while loop and it correctly lists out everything it needs to:
<input type='checkbox' name='rep[]' value='$invoiceID'>Reference Number: $invoiceID
<input type='hidden' name='billablehours[]' value='$billableTotal'>
When the form is submitted the values are inserted into the database using:
foreach ($_POST['rep'] as $index => $id) {
$sql2="INSERT into b_sale_basket (QUANTITY,LID,NAME)
VALUES
('".$_POST['billablehours'][$index]."','s1','".$_POST['rep'][$index]."')";
if (!mysqli_query($con,$sql2))
{
die('Error: ' . mysqli_error($con));
}
}
It inserts everything as it should do except billablehours. I have outputted the value of $billableTotal on each checkbox on the form page and the value is correct. For example it might equal 25 but when the button is pressed it inputs 37.5 which is another value of a checkbox.
Strange. Can anybody identify an issue?

Problem is that if checkbox is not checked it's not passed to server, so if u have 3 checkboxes and select first and third, on server you got them with 0, 1 index.
in your case just use specific identifiers:
<input type='checkbox' name='rep[$id]' value='$invoiceID'>Reference Number: $invoiceID
<input type='hidden' name='billablehours[$id]' value='$billableTotal'>
Assuming you know this $id is connected corresponding $invoiceID and $billableTotal,
it may be entry id from database.
And when using: $_POST['billablehours'][$index] if checkbox is not checked it gots empty...
Note: my exmplanation is just to understand the point, not 100% working example maybe, because I've got no full code what you do.
Just remember: It's the key when working with checkboxes to correctly reference the data passed from server to client and vs.

Only checked checkboxes are submitted. So if you only check one, then rep array will only have one element 0 but thebillablehours array will have as many as are defined on the page.
$i = 0;
//loop
echo "<input type='checkbox' name='rep[$i]' value='$invoiceID'>Reference Number: $invoiceID";
echo "<input type='hidden' name='billablehours[$i]' value='$billableTotal'>";
$i++;
//end loop
So the rep and billablehours indexes will match regardless of how many checkboxes were checked.

You are wide open to SQL injection attacks with your script. You either need to use prepared statements (preferable) or run your $_POST values through mysqli_real_escape_string;
Leaving my incorrect answer below, but not deleting this answer because I think the SQL injection vulnerability needs to be addressed.
That being said, your issue is that you aren't echoing the value:
value='<?php echo $billableTotal; ?>'>

Make these changes:
name="billablehours[$invoiceID]"
$_POST['billablehours'][$_POST['rep'][$index]]

Related

How to separate checkbox variable results outputted in a while loop in PHP?

I'm trying to write an attendance system that, when a user is present at a class, the staff will check a box and the program will then add one to the present count of the relevant customers. The problem is to output the register, taken from phpMyAdmin, it uses a while loop so all the checkboxes have the same variable name. This is the code I have so far...
echo "<form 'action=badminreg.inc.php' method='post'>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row['bookingID']."</td><td>".$row['firstName']."</td><td>".$row['surname']."</td><td><input type='checkbox' name='present' value='present'</td><td><input type='checkbox' name='incident' value='incident'</td></tr>";
}
echo "<input type='submit' name='reg-submit'>";
echo "</form>";
isset($_POST['reg-submit']);
$pres = $_POST['present'];
I need to separate the check box inputs so that the program will be able to mark individual users differently to others. I'm sort of new to PHP as this is for my A-level coursework so is there a way to get around this? Any help would be great. Thanks
You can define the name for the checkbox elements as array and pass the bookingID as value.
Example (untested):
$output = "<tr><td>{$row['bookingID']}</td><td>{$row['firstName']}</td><td>{$row['surname']}</td><td><input type='checkbox' name='present[]' value='{$row['bookingID']}'</td><td><input type='checkbox' name='incident[]' value='{$row['bookingID']}'</td></tr>";
The variables $_POST['present'] and $_POST['incident'] contains then an array with the IDs of the selected check boxes.
If you change it to name='present[]' then when you submit the data again, you'll get an array of values inside $_POST["present"] instead of a single one. (You'll get one item in the array for each checkbox with that name which was actually checked - a quirk of HTML forms is that if the checkbox wasn't checked, its value is not submitted at all).
You'll also want to change the value of the checkbox to be the ID of the customer (or booking, maybe), so you can identify which box was checked.
Same for the "incident" checkbox as well, of course.
So you're aiming for something like this, I think:
echo "<tr>
<td>".$row['bookingID']."</td>
<td>".$row['firstName']."</td>
<td>".$row['surname']."</td>
<td><input type='checkbox' name='present[]' value='".$row['bookingID']."'</td>
<td><input type='checkbox' name='incident[]' value='".$row['bookingID']."'</td>
</tr>";

How to insert data without knowing no off columns in php

I have a variable number of fields in a table,where the number of column headings are directly fetched from database,so the number of heading increases as the data from database increase(eg-demo,demo1,demo2,..).For each column there is a selectbox,here i have given name for check box as txtcheck".$i."[] where $i is set as an incriminating value.
<input type='checkbox' name='txtcheck".$i."[]' value='1'>
My doubt is how can i fetch the checkbox post value when form submission.I dont know whether this is correct way nor find a way to efficiently do this. Please advise.
The name of your checkboxes shouldn't be incremented, but only be txtcheck[]. In this case the selected boxes will be transfered as array.
<input type='checkbox' name='txtcheck[]' value='1' />
In your PHP code you can access this array with $_POST['txtcheck'].
<?php
$checkedBoxes = $_POST['txtcheck'];
foreach ($checkedBoxes as $checkdBox) {
// Here you can handle each box that was checked in your form, e.g. echo it's value
echo $checkedBox . ' ';
}
?>
So if you checked e.g. boxes with values 1, 5 and 10 your output will be 1 5 10

PHP update is not updating database with checkbox

to all i have a weird problem when i am trying to update a table of my database with checkboxes it takes only one value and all the rest just ingnores them here is my php code so far
foreach ($_POST['choice'] as $id){
$price=$_POST['price'][$id];
$availability=$_POST['availability'][$id];
$result1=mysql_query("UPDATE store SET storeid='".$id."',availability='".$availability."', price='".$price."' WHERE productid='".$par1."'");
}
Yes you are right and i am deeply sorry for the lack of information.Here is my html code as well
echo "<td><input type='text' id='availability[".$row->id ."]' name='availability[".$row->id ."]' value='".$row->diathesimotita ."' size='20'/></td>";
echo "<td><input type='text' id='price[".$row->id ."]' name='price[".$row->id ."]' value='".$row->price ."' size='10'/></td>";
echo "<td><input type='checkbox' id='choice[".$row->id ."]' name='choice[".$row->id ."]' value='".$row->id ."' /></td>";
echo"</tr>";
So i am trying to take the textbox values which are in the same row with the check box but it gets only the first checked ckeckbox
Checkboxes only post a value when they are checked. You should validate them or set a value first before trying to use them in a query (for security if nothing else!). For example do this at the top of your processing code:
$checkbox_val = (!empty($_POST['choice']) ? 'Yes' : 'No'); //example only assuming non-array for 'choice'
This will set the value to 'No' if the POST value is empty or not set, guaranteeing that you always have a value. You can change the values to 0/1, true/false, etc.
Also, without seeing what is in your 3 $_POST arrays, it is impossible for us to tell you if you are getting the correct values for $price etc.
The PHP code looks fine; we need to see the HTML code, but anyway try this in SQL:
UPDATE store SET storeid='".$id."' , availability='".$availability."' , price='".$price."' WHERE productid='".$par1."'" );
Spaces really matter in SQL. If this does not work please show us the HTML code.

Return value from element while showing another

Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]

save data in form of arrays to mysql database using a foreach loop

I have a form that submits multiple values using php. code is below:
echo "<form action='?ud=".$ud."' method='post'>Name: <input type='text' name='fname' />";
$resultw = mysql_query("SELECT * FROM options where userid='$ud' ORDER BY priority ASC");
while($row = mysql_fetch_array($resultw))
{
echo "
<input type='hidden' name='widgetid[]' value='".$row['widgetid']."' />
<span id='".$row['widgetid']."' style='color:white;font-size:13px;'>".$row['items'] . "</span><br></div><div style='' class='portlet_content'>
Enabled <input title='Enabled/Disabled' type='checkbox' value='enable[]' name='enable[]' ".$checked." id='checkbox".$row['id']."' />
Height <input title='set height' name='height[]' value='".$row['height']."' type='text' name='textfield' id='textfield".$row['id']."' />
";
}
echo '<input type="submit" /></form>';?>
as you can see its a loop thats get the values from db and echoes a form. I made it as simple as possible it has more input boxes but i removed them and removed the styling to make it simpler to read. when I hit Submit I would like to be able to have all those values updated to the database through a loop.
I tried foreach and struggled. any suggestions
First of all, your code has a security bug in that you are directly putting a variable into a SQL query. That allows for SQL injection. Instead, you should put the variable $ud through mysql_real_escape_string before inserting into the query or, significantly better, use MySQLi/PDO and prepared statements.
Have you checked that the form is correctly echoed onto the page? View the source (or use Firefox and Firebug) to double check that it has been properly inserted.
Then you will need to have a code block that is initiated when it receives a POST request. That code will get an array back for each of your variables e.g.
$widget_ids = $_POST['widgetid']; #this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
You can do this for each of your POSTed variables and then just loop round the widget ids doing an update query for each one e.g.
$i = -1;
foreach($widget_ids as $widget_id) {
$row_enable = $enable[++$i];
$row_height = $height[$i];
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
}
Just to be pedantic, your HTML is also a bit messy and incorrect. For a form I would use label elements for each label and don't use br's for new lines. You also have a div with no beginning and then a div with no ending.

Categories