I am going nuts here, I have an array of checkboxes from a form that I am trying to $_POST with PHP. EVERYTHING on my form posts fine except the check boxes. The checkboxes DO post, but in the wrong order. For instance when I want checkbox[0] and checkbox[2] I actually get checkbox[0] and checkbox[1].
I have tried many different ways to get the value of the checkbox, including isset but I still have the same problem. I just need the checkbox value of on to be stored in my database if the checkbox is indeed checked.
My code is below. $in_production is the checkbox. I can provide the code that generates the checkbox too if it is needed.
Thanks in advance.
if ($_GET['action'] == 'Edit_Product'){
include("../dbinfo.php");
$q_id = $_GET['q_id'];
for ($i = 0; $i < count($_POST['p_id']); $i++){
$result = mysql_query('SELECT * FROM products WHERE q_id = '.$q_id);
$num = mysql_num_rows($result);
$p_id = ($_POST['p_id'][$i]);
$in_production = ($_POST['in_production'][$i]);
$p_name = ($_POST['p_name'][$i]);
$p_price = ($_POST['p_price'][$i]);
$p_name_conflict = FALSE;
for ($ii = 0; $ii < $num; $ii++){
$row = mysql_fetch_array($result);
$p_name_conflict_check = $row['p_name'];
$p_id_conflict_check = $row['p_id'];
if($p_name_conflict_check == $p_name &&
$p_id_conflict_check != $p_id){
$p_name_conflict = TRUE;
}
}
if ($p_name_conflict == FALSE){
$query = "UPDATE products SET p_name='$p_name',
p_price='$p_price', in_production='$in_production',
last_modified=CURDATE() WHERE p_id = '$p_id'";
mysql_query($query);
}
else{
$update_failures =+1;
}
}
mysql_close($link);
if($update_failures == 0){
header("Location: Products_Updated.html");
}
elseif ($update_failures != 0){
header("Location: Products_Exist.php?update_failures=".$update_failures);
}
}
P.S. I don't know why but the code block icons are not present on SO right now... so my code is not all pretty. Also, I know my code is horribly inefficient, but I am just trying to get this working right now, then fine tune later. I am open to efficiency suggestions as well, but that is not my primary objective with this question.
EDIT: Here is the form from the HTML...
<form id="form" name="form" method="post" action="/Management/Products/Product_Management.php?action=Edit_Product&q_id=<?php echo "$q_id" ?>">
<?php
include("../dbinfo.php");
$result = mysql_query('SELECT * FROM products WHERE q_id =' . $q_id);
$num = mysql_num_rows($result);
mysql_close($link);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$p_id = $row['p_id'];
$p_name = $row['p_name'];
$p_price = $row['p_price'];
$in_production = $row['in_production'];
$date_added = $row['date_added'];
$last_modified = $row['last_modified'];
if($in_production == 'on'){
$checked = 'checked';
}
else{
$checked = '';
}
echo "<div>Product ID# " . $p_id . "<label style=\"font-style:italic\"> (Originally added on " . $date_added . ", last modified on " . $last_modified . ")</label></div><br/>";
echo "<input id=\"p_id" . $p_id . "\" class=\"text\" type=\"hidden\" name=\"p_id[]\" value=\"" . $p_id . "\"/>";
echo "<label>Product Name *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Product still in production <input type=\"checkbox\" name=\"in_production[]\"" . $checked . " style=\"width:15px\"/>)</label></div>";
echo "<input id=\"p_name" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_name[]\" maxlength=\"20\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_name . "\"/><br/><br/>";
echo "<label>Product Price *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Without taxes)</label></div>";
echo "<input id=\"p_price" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_price[]\" maxlength=\"6\" onkeypress=\"return currency(this, event)\" onchange=\"currency_format(this)\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_price . "\"/><br/><br/><br/><br/>";
}
?>
<input class="button" type="button" value="Submit" onclick="product_edit_form_check()"/><br/><br/>
</form>
It would be helpful if you could post some of the HTML-part so we could see how you create your form. It seems you're generating your checkboxes without indexes in your array, so all checkboxes have the name/id "checkbox[]", which is ok if you don't care about the index, but if posted, the array will be numbered starting from "0" and then counting up which is the reason why you'll get "0" and "1" posted, even if "0" and "2" were checked.
Try to give your checkboxes' name/id numbers when generating the HTML, like "checkbox[0]", "checkbox[1]", "checkbox[2]", and so on. So when checkbox 0 and 2 are checked, you should get those values (including the correct index) posted.
The thing you have to bear in mind with HTML checkboxes is that they only POST a value if they are checked. If they are not checked, they don't get posted.
With this in mind, you should give each checkbox a name and then test for it in the POST to detect whether or not it has been passed back.
if (isset($_POST['MyCheckbox'])) {
} // else it wasn't checked!
Show us the HTML for the checkboxes.
Also, you have an SQL injection attack waiting to happen - a user can get any SQL they like onto the end of your query. Something like this illustrates what you should do with untrusted data:
//we're expect a number, so ensure we get one
$q_id = intval($_GET['q_id']);
//get into the habit of quoting query params,
//or better yet, use a wrapper library to help you
$sql="select * from products where q_id='".mysql_real_escape_string($q_id)."'";
If you declare checkbox name like (p_id[]), it's like telling PHP "I'm adding element to an array, enumerate it for me". Like in php $array[] = 't'; If you have several form elements with different names and you want to have synchronised IDs you HAVE to add index because otherwise browser will/may send only selected ones and PHP will enumerate it continuously.
You can specify indexes by using p_id[INDEX] and so on, where index is anything (I suggest numeric or alphanumeric).
Also, checkbox value can be altered and I encourage you to do it. value="1" helps, then you're sure that you get it.
<input type="checkbox" name="p_id[0]" value="1" />
In PHP you'll receive
$_POST['p_id'] ===> array(0 => 1);
et caetera.
Related
I have a Database (MySQL) where is a table called: "dbtest" has the following fields,
id + v + o1 + o2 + o3 + o4 + g
to clarify that:
v: are the questions field
o1: the first answer
o2: the second
o3: third
o4: forth
g: is the right answer, where I put the number of the right answer for example, if I had a question with a correct answer "o3" the value of "g" should be "3"
(I did that myself thinking would be easier hopefully)
We yet did not reach the point I know, the thing is that I'm building a quiz program standing on the previous scheme, I made a page that calls the questions from the database and post them one below the other, the code was as the following:
<?php
include "config.inc";
$SQL = "SELECT * FROM test";
$query = mysql_query($SQL) or die();
echo "<form action=grade.php method=POST>";
while ($row = mysql_fetch_assoc($query)) {
echo "<p>$row[id]. ";
echo "$row[v]<br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o1]>$row[o1]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o2]>$row[o2]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o3]>$row[o3]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o4]>$row[o4]</input><br>";
}
echo "<input type=submit name=submit value=Check>";
echo "</form>";
?>
The problem is when I wanted to write the "grade.php" page I fell off an edge, I absolutely lost, I could do it if there was just one question in the database, so no need to enter a loop, but since the database is expected to receive tons of question I lost control.
I was trying something like,
<?php
include "config.inc";
$SQL = "SELECT * FROM test";
$query = mysql_query($SQL) or die();
$n = 0;
while ($row = mysql_fetch_assoc($query)) {
$n++;
$ques[$n] = $_POST['answer'];
if ($ques[$n] == $row[g]) {
echo "<font color=green>Correct</font>"; }
else {
echo "<font color=red>Incorrect<br></font>"; }
}
?>
But did not make it, all what I need is to process the questions and give right/wrong answers, for every right answer (+1) for every wrong one (-1) then I will post the sum mathematically.
In HTML your have to change radio button :
No need to add </input>,
For value you set answer number,
Add quotes for attributes
echo '<input type="radio" name="'.$answer[$row['id']].'" value="1" />'.$row['o1'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="2" />'.$row['o2'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="3" />'.$row['o3'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="4" />'.$row['o4'].'<br>';
In PHP :
You create some variables to store good and bad answers,
You check if value of $row['g'] is equal to answer number
$query = mysql_query("SELECT * FROM test") or die();
$good = 0; // Number of good answers.
$bad = 0; // Number of bad answers.
while ($row = mysql_fetch_assoc($query))
{
if ( $_POST['answer'][$row['id']] == $row['g'] )
{
echo '<span style="color: green;">Correct</span>';
$good++;
}
else
{
echo '<span style="color: red;">Incorrect</span>';
$bad++;
}
}
the form already has an existing submit button which you can select difficulty(1st combo) and location(2nd combo) and then i submit this to display a video and a text field
under the field i have an addtional drop down box which is yes or no
then inside this code i want to submit a separate value using an if inisde an if it works fine on the 1st difficulty and location in the lists but nothing else and i cant see what im doing wrong a new pair of eyes would be great PS i will be upgrading this to PDO eventually
<?php
if(strpos($drop, 'norm') !== false && $ruavalue == 0)
{
Echo "RUA: ";
$RUAresult = mysql_query("SELECT Answer FROM options");
echo "<select name='ruacombo'>";
while($RUArow = mysql_fetch_assoc($RUAresult))
echo "<option value = '".$RUArow['Answer']."'>".$RUArow['Answer']."</option>";
echo "</select>";
echo '<form action="" method="post">';
echo "<input name=\"boss\" type=hidden value=".$_POST['tier_two'].">";
echo "<input name=\"main\" type=hidden value=".$_COOKIE['ID_my_site'].">";
echo '<input type="submit" name="ruasubmit" value="RUA!" />';
echo '</form>';
if (isset($_POST['ruasubmit']))
{
$ruaboss = $_POST['boss'];
$ruauser = $_POST['main'];
$ruasql = "UPDATE `RUASEXCELL` SET `$ruaboss`=1 WHERE Username = '$ruauser'";
$add_rua = mysql_query($ruasql);
}
In your while loop, you need to access the associative array keys as a string like so:
while($RUArow = mysql_fetch_assoc($RUAresult))
echo "<option value = '".$RUArow['Answer']."'>".$RUArow['Answer']."</option>";
Also, please look into using mysql_real_escape_string() to prevent SQL injection. In its current state, this script, and your database can be blown to pieces by a stray quote.
First off, I want to store the names of these checkboxes which are submitted, and not their values.
This is my code:
<?php
$con=mysqli_connect("localhost","root","","notifier");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student");
echo "Enter the attendance. Please untick for 'ABSENT' students and submit";
echo "<br>";
echo "<form action=\"d.php\" method=\"post\">";
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
}
echo "<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
?>
This code simply fetches a column of student rollnumberss from student table, prints them, and as well as prints a checkbox infront of them which is checked by default.
Names of checkboxes will be the student id (varchar, another column).
Now since All Checked checkboxes, that is the checboxes which will be submitted to next page will have same default value "P", I m not concerned about their values.
How do I store the names of these checkboxes in an array, and later on use it to perform updation in table for all these student id's?
Use the following code:
while($row = mysqli_fetch_array($result))
{
echo '<br>' .$row['classrollno'] . ' <input type="checkbox" name="studentId[]" value="' . $row['studentid'] . '" checked />';
}
Then, when you process the form, the $_POST['studentId'] variable will contain an array with all the id's.
Since the value that will probably be inserted in the db is 'P' for every student, you wouldn't need to include it in your form, but just hardcode it in your query.
Keep adding the names to an array. Its straight forward.
Declare $allStudentIds = array(); outside while loop. Then, to store in that array,
$allStudentIds[] = $row['studentid'];
Since you wanted to use these values later, you can directly store them inside a session variable:
$_SESSION['allStudentIds'][] = $row['studentid'];
In above case, $_SESSION['allStudentIds'] will be an array of all student ids selected.
Note: You need to start session using session_start() as the first line in the script after opening <?php tag.
Simply, in the fetching while loop, define an array and set each checkbox value to one of its elements then assign it as a session variable:
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
$names[] = $row['studentid'];
}
Then,
$_SESSION['names'] = $names;
Your confusion seems to stem from the fact that you are mixing the View (the name of the checkbox in HTML) and the Model/Data (which the student_id you are getting from your DB query ie. the $row = mysqli_fetch_array($result) in the while loop).
All you need to do is create an empty array (eg. $studentid_arr) before the loop and after the echo statement which is just contributing to the view (the HTML) you do some work with your data. What you want to do currently is to store the student_ids (and not the name of the checkbox) in your $studentid_arr.
That can be done with a simple array_push ($studentid_arr,$row['studentid']);
So your while loop would look like
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
array_push ($studentid_arr,$row['studentid']);
}
Now you can just POST this PHP array to your next script which is expecting these values. (which is what I assume you mean by submitting to the next page)
I have a list of checkboxes and save the checked values in an array. However, when someone clicks 'submit' and they get an error, all their checked boxes are forgotten. Usually I would let the script remember the checked boxes with a code like
IF checkbox value = OK { echo checked="checked"}
However, now I save it in an array and I have no idea how to do this?
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
}
?>
This is the code I use for the checkboxes. Next I display the array with this code:
$merkenstring = implode(",", $_POST['merken']);
echo $merkenstring;
Result: AC Ryan,Adidas,Agu,Cargo
I hope someone could give me a code example!
Assuming you are posting this to the same page, and $_POST['merken'] is still available after an error, use in_array() to test each checkbox's value against the current set in $_POST:
while ($row = mysql_fetch_array($result)) {
// If the current value is in the $_POST['merken'] array
// and the array has been initialized...
if (isset($_POST['merken']) && is_array($_POST['merken']) && in_array($row['merknaam'], $_POST['merken'])) {
// Set the $checked string
$checked = "checked='checked'";
}
// Otherwise $checked is an empty string
else $checked = "";
// And incorporate it into your <input> tag
echo " <input $checked type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
//----------------------^^^^^^^^^^
}
If this was posted to a different script, you would (as with any post value returned to a previous script) need to store the array in $_SESSION instead and compare against $_SESSION['merken'] in your in_array() call.
Assuming $row['merknaam'] is the checkbox value, and $_POST['merken'] holds an array of checked checkbox values, then you simply need to check if the value is in the array:
if (in_array($row['merknaam'], $_POST['merken'])) {
// this checkbox should be checked
}
I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.