I have an issue when trying to insert info coming from a form which is generated dynamically in php.
The form consists of of an variable amount of inputs which all consists of four input elements. See below how my form is generated:
<?php $result = mysql_query("SELECT id,name,description FROM todo_q WHERE todo_id = $todo_id AND active = 'y'");
while($todo_q=mysql_fetch_array($result)){
echo '<label>';
echo $todo_q['name'];
echo '</label><br>';
echo '<input type="checkbox" name="value[]" value="y" />';
//echo '<input type="hidden" name="value[]" value="n" />';
echo '<label>';
echo $todo_q['description'];
echo '</label><br>';
echo '<input type="text" id="comment" name="comment[]">';
echo '<input type="hidden" name="user_id[]" value="';
echo $user_id;
echo '" />';
echo '<input type="hidden" name="todo_id[]" value="';
echo $todo_q['id'];
echo '" />';
echo '<HR>';
}?>
And this is how I try to insert the info into mySQL:
$query = "INSERT INTO todo_a (value, comment, user_id, todo_id) VALUES ";
$query_parts = array();
for($x=0; $x<count($_POST["value"]); $x++){
$query_parts[] = "('" . $_POST['value'][$x] . "','" . $_POST['comment'][$x] . "'," . $_POST['user_id'][$x] . "," . $_POST['todo_id'][$x] . ")";
}
$q_parts = $query_parts;
foreach ($q_parts as $q_p){
$insert = ($query .= implode(',', $query_parts));
$result = mysql_query($insert);
}
The problem I have is that when check all checkboxes and comments everything is inserted on the right row in the DB, but if I skip to check one checkbox then it gets messed up...
I would like it the insert a new row if it the checkbox is checked and/or a comment is entered.
Can anybody point me in the right direction?
I tried to put a hidden input to get the value of unchecked checkboxes but i doesn't seem to work.. That why I have commented out the hidden checkbox.
PS. I know I should be using mysqli but this is an older site that I haven't upgraded yet..
You need to add index into input checkbox and comment name like :
$cbIndex = 0;
while($todo_q=mysql_fetch_array($result)){
echo '<label>';
echo $todo_q['name'];
echo '</label><br>';
// Generate checkbox with index of current result
echo '<input type="checkbox" name="value[' . $cbIndex . ']" value="y" />';
// Generate comment with index of current result
echo '<input type="text" id="comment" name="comment[' . $cbIndex . ']">';
echo '<input type="hidden" name="user_id[' . $cbIndex . ']" value="';
echo $user_id;
echo '" />';
echo '<input type="hidden" name="todo_id[' . $cbIndex . ']" value="';
echo $todo_q['id'];
echo '" />';
echo '<HR>';
// Inc of index
$cbIndex++;
}
When you submit your form, only checked checkbox will appear in $_POST["value"] :
foreach ($_POST["value"] as $cbIndex => $cbValue) {
$query_parts[] = "('" . $_POST['value'][$cbIndex] . "','" . $_POST['comment'][$cbIndex] . "'," . $_POST['user_id'][$cbIndex] . "," . $_POST['todo_id'][$cbIndex] . ")";
// or
$query_parts[] = "('" . $cbValue . "','" . $_POST['comment'][$cbIndex] . "'," . $_POST['user_id'][$cbIndex] . "," . $_POST['todo_id'][$cbIndex] . ")";
}
...
Btw, you don't need to store value of checkbox, that will be 'y' all the time.
INFO That will be fine for a test app, but as commented by #Pogrindis and #John Conde, it's not safe code. MySQLi/PDO + prepare statement will avoid SQL injection.
Related
I have a need to check the checkboxes which values are available in the database, with that i has to display additional options avaialable also.
I was trying, as i am using two loops it's repeating the same set of checkboxes and check differnt values in each instance.
I need to check the appropriate checkboxes in first loop itself. Is there any way to achieve this
The following was my output
Output of the code
Following is the code i am using
$sid;//Retrived from DB
$iDLst=array();
$sql1 = "SELECT
`id1`
FROM `tbl1`
where `tbl1_sid`='" . $sid . "'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$iDLst[]=$row['id1'];
}
}
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
}
}
}
Note: I have changed to general code, There is no errors in code. I am getting the display. I need the solution regarding the logic part...
I think you can replace this:
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
with this:
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" ' . strpos($rowC['id'], $id) ? 'checked ' : '' . '/> <label>' . $rowC['nme'] . ' </label>';
It's a ternary statement that says if strpos($rowC['id'], $id) evaluates true, 'checked ' will be in the enclosing echo statement, otherwise '' will be in the enclosing echo statement.
I have found the way after some research.
The way i am doing is only half part.
Following code will do the work addition to the provided code.
//Print the checkbox with checeked for the values in array
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
}
}
}
//Print the checkbox without checeked for the values Not in array
$sql3 = "$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2` where id NOT IN (" . implode(',', array_map('intval', $iDLst)) . "); ";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
while ($rowC = $result3->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]"/> <label>' . $rowC['nme'] . ' </label>';
}
}
the following questions lead me the way to do this
MySQL PHP - SELECT WHERE id = array()? [duplicate]
mysql syntax on not equal many values
I have something like this in my code:
<?php
foreach ($tomb2[1] as $key => $metaname){
$talalat = $tomb[1][$key];
echo '<p>' . "$metaname\n" . '</p>' . '<br>' . '<input type="text" name="metavalue[]" value="' . "$talalat\n" . '">' . '<br>';
}
?>
<input type="submit" name="Generálás" value="insert" onclick="insert()" />
</form>
I try to echo the several different values, however I get only the last one. Possibly the array contains only the last one. What am I doing wrong?
if you use a post method in form then you have to written $ertekek = $_POST["metavalue"] instead of $_GET["metavalue"] and then use print_r($ertekek)
instead of echo $ertekek;
You have written $talalat = $tomb[1][$key]; instead of $talalat = $tomb2[1][$key];
I'm working with an examination page using php connected to a MySQL database. I'm currently on the part where i need to check if the the answers checked on the radiobutton is correct.
QUESTION: How will i know which radiobutton is checked, and how will i know if the answer on that radiobutton is equal to the data in the database? I want to display the "CORRECT" if it's the same or "INCORRECT" if it's wrong in a different page.
Here is my PHP code for the radiobuttons:
$sql = 'SELECT q_question, q_correct, q_answer2, q_answer3, q_answer4 FROM tblquestions WHERE q_category = "' . $legend3 . '" ORDER BY rand() LIMIT ' . $limit3;
$retval = mysql_query($sql,$conn);
if(!$retval)
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$span1 = $row['q_question'];
$obj1 = $row['q_correct'];
$obj2 = $row['q_answer2'];
$obj3 = $row['q_answer3'];
$obj4 = $row['q_answer4'];
$my_array = array($obj1, $obj2, $obj3, $obj4);
shuffle($my_array);
$rad1 = $my_array[0];
$rad2 = $my_array[1];
$rad3 = $my_array[2];
$rad4 = $my_array[3];
echo '<table width="100%" border="0" cellpadding="1" cellspacing="1">';
echo '<tbody><tr><td colspan="2" width="300" height="40"><span id="question1">' . $count . '. ' . $span1 . '</span></td></tr>';
echo '<tr><tbody><tr><td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1A]" value="'. $rad1 .'">A. ' . $rad1 . '</td>';
echo '<td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1B]" value="' . $rad2 . '">B. ' . $rad2 . '</td></tr></tbody></tr></tbody>';
echo '<tr><tbody><tr><td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1C]" value="' . $rad3 . '">C. ' . $rad3 . '</td>';
echo '<td width="50%"><input name="q' . $nameCTR1 . '" type="radio" class="validate[required] checkbox" id="a[I1D]" value="' . $rad4 . '">D. ' . $rad4 . '</td></tr></tbody></tr></tbody></table>';
echo '<hr width="100%"></hr>';
$nameCTR1 = $nameCTR1 + 1;
Checkbox and radio type filed does not get posted when they are unchecked or not-selected.
So in your action script(the one which you have set in action attribute of form) you can check whether their value has been set in $_POST (if your form method is POST) or not.
If it exist then it implies that fields are checked or selected else not.
I made a function for you. Just call the function getRadio(name of radiobutton here) and it will return the value if it was checked.
function getRadio( $radioName ) {
$radio = $_POST[ $radioName ]; // RADIO NAME IS DEFINED IN HTML
if( isset( $radio ) ) {
return $radio;
}
return $radioName . " is not set";
}
*Also this assumes you are using the post method
Here is the code that displays the table in a form where you are to insert manually only the last field.
After filling you should go ahead and save the form into the database, but since there are no specific number of input fields (as they will vary), I need to use an array to capture all the data.
$quam = mysqli_query('select * from locstock where loccode="' . $loc . '"') or die(mysqli_error());
while ($row = mysqli_fetch_array($quam)) {
echo '<tr><td>' . getItemcode($row['itemid']) . '</td>';
echo '<td>' . getItemname($row['itemid']) . '</td>';
echo '<input type="hidden" value="' . ($row['itemid']) . '" name="itemid[0][]">';
echo '<td>' . ($row['quantity']) . '</td>';
echo '<input type="hidden" value="' . ($row['quantity']) . '" name="iquant[0][]">';
echo '<td><input type="text" title="Enter Manual Count" placeholder="Enter Manual Count" name="tally[0][]"></td>';
echo '</tr>';
}
How can I retrieve the data?
You can easily count() your INPUT fields data. as your values are part of array -> name="iquant[0][]" you can easily process them. See output of print_r($_POST); after submitting your form.
I have an code that gets the 'branches' from the database. Each company can have multiple 'branches'.
Only thing is, that is doesn't work. Can you guys figure out what's wrong?
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while($rijbranche = mysql_fetch_assoc($querygetbranches))
{
echo "<tr>";
echo "<td width='400'>";
echo $rijbranche['naam'];
echo "</td>";
echo "<td>";
$get2 = "SELECT * FROM bedrijf_branche WHERE bedrijf_id = '$id'";
$query2 = mysql_query($get2);
while ($rij20 = mysql_fetch_assoc($query2))
{
$branche_id = $rij20['branche_id'];
}
if($branche_id == $rijbranche['id_branche']){
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" CHECKED></input>
<?php
}
else
{
?>
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>"></input>
<?php
}
echo "</td>";
}
Try the following code
<?php
$id = $_GET['id'];
// Output BRANCHES
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);
while ($rijbranche = mysql_fetch_array($querygetbranches)) {
echo ' <tr>' . "\n";
echo ' <td width="400">' . $rijbranche['naam'] . '</td>' . "\n";
// Output CHECKBOX
$get2 = mysql_query("SELECT * FROM bedrijf_branche WHERE bedrijf_id = '" . $id . "' AND branche_id = '" . $rijbranche['id_branche'] . "'");
$rij20 = mysql_fetch_array($get2);
$branche_id = $rij20['branche_id'];
if ($branche_id == $rijbranche['id_branche']) {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" checked="checked" />';
}
else {
$checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" />';
}
echo ' <td>' . $checkbox . '</td>' . "\n";
echo ' </tr>' . "\n";
}
?>
Found a couple of errors I fixed in the above code.
You're closing the <input> fields incorrectly
Your second while() loop is unnecessary as there should only be one row returned
You have to add branche_id to your second mysql_query!
Don't close and re-open your <?php ?> tags for every HTML line when you can just add an echo
Your HTML-syntax is wrong.
The way you close the input tag and the way you want to check the chechbox is wrong
Try this
<input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" checked="checked" />