php checkbox from mysql - php

I've managed to pull records from a mysql database using php with a checkbox to select. I'm struggling to make the selected records (with the checkboxes) appear on a new page. Here is my code so far:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' /></td>
</tr>";
}
print "</table>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
<html>
<form action="check2.php" method="POST">
<input type='submit' name='Submit' value='Submit'>
</html>
And on the page where I want the selected records to display, I have:
<?php
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
Any assistance would be appreciated!

Put checked="checked" just like you have put value="check":
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' checked="checked" /></td>
Edit:
Probably I misunderstood you. What do you expect to see?
First, you should make the form to perform POST request instead of GET (default):
print "<form method='POST' action='THE_FILE_YOU_PRINT_RESULTS.php'>"
Then in "THE_FILE_YOU_PRINT_RESULTS.php" do a print_r($_POST); to see what you get and how to display it.

A better way to do this would be to name your checkboxes check[]. Each checkbox value should then be the ID (rather than check).
Then on your results page, just loop through each instance of check[] and print the value out.

check[$row{['GradeID']}]
Seems incorrect to me, should it be:
check[{$row['GradeID']}]
Notice the moved opening curly bracket to before the $
Sorry if this is wrong haven't used PHP in long time but it stood out for me

The are a couple of error in the form print function.
You have to put the action on the first form, not on the second, you have to change the way how you print the checkbox as well.
Try to print the form in this way:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "
<form action=\"check2.php\" method=\"POST\">
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[".$row['GradeID']."] value='".$row['GradeID']."' /></td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
And print the checked box reading the _REQUEST array:
<?php
if(isset($_REQUEST["check"]))
{
foreach($_REQUEST["check"] as $key=>$value)
{
echo $key."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
This should work.

Related

PHP update SQL from multiple HTML checkbox

So, I need to make sure this sets the right parameters to the DB when pressing the buttons. I just want to get the calls and comparisons right so it does what it should when I hit the buttons. There should be one delete button for each row from database, and update page when I press it.
It should be possible to update the text/numbers in the forms presented by MySQL by changing the forms and press Save-button, then refresh the page.
$counter = 1;
if(isset($_POST['save']) and something is changed from the forms compared to DB) {
Update MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
if(isset($_POST['del'])) {
DELETE MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
echo "<tr><td>ID</td><td>Namn</td><td>Platser</td><td>Fullbokad</td><td>Ta bort</td></tr>";
$sqlListSections = "SELECT * FROM avdelningar WHERE user = {$_SESSION['id']}";
$queryListSections = mysqli_query($mysqli, $sqlListSections);
$del = [];
while($rowListSections = mysqli_fetch_array($queryListSections))
{
if($counter%2)
{
echo "\n<tr bgcolor=#F1F1F2>\n\n";
}else
{
echo "\n<tr bgcolor=#FFFFFF>\n\n";
}
$counter++;
echo "
<td>".$rowListSections['id']."</td>
<td>
<input type=text value=".$rowListSections['namn']."></td>
<td>
<input type=text value=".$rowListSections['platser']."></td>
<td>";
if($rowListSections['prio'] == 1)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='0'>0</option>".$rowListSections['prio'];
}elseif($rowListSections['prio'] == 0)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='1'>1</option>".$rowListSections['prio'];
}
echo "</td>
<td>
<form method=post action=thispage.php>
<input type=submit value=Delete name=del>";
</td>
</form>
</tr>";
}
echo "<form method=post action=thispage.php>
<input type=submit value=Save name=save>";
`
in your checkbox change naming as array.
<input type=checkbox name="del[]" value={$rowListSections['id']}>
like
echo $rowListSections["id"].' '.$rowListSections["namn"].' '.$rowListSections["platser"].' '.
$rowListSections["prio"].'';
and in your if(isset($_POST)) you can get a del array so you can loop this array like below.
foreach($del as $val){
$id = $val;
$sql_query_for_update = "update table_name set field = 1 where id= '$id' ";
}

multi if and elseif statement in form

I have a form on a single page, if it don't have a id I want it to insert. but if there is an id then update.
I am having difficulties getting the form values to display in the button.
I am also not sure my if or else if statement is plausible.
<?php
function myform(){
if(isset($_POST['add'])) {
if ($myform_id > 0) {
//my insert query here
$btn_value = "add";
$btn_name = "add";
}elseif(isset($_POST['edit'])){
//my update query here
$btn_value = "edit";
$btn_name = "edit";
}
}
}
?>
My form button
<input type="submit" name="<? $btn_name?>" value="<? $btn_value?>">
try this
<input type="submit" name="<?echo $btn_name;?>" value="<? echo $btn_value;?>">
within the php tag itself give the following statement
print "<input type='submit' name='$btn_name' value='$btn_value'>";

form checkbox value php

I have a form created by a while loop in php like this :
<form action='#' method='post'>
<input type='hidden' name='form_valid' id='form_valid'>
<?php
$i=-1;
$result_array = array();
//the while is from a simple mysql query
while( $line = $results->fetch() )
{
$i++;
echo"<input type='checkbox' class='checkbox' value='".$line->nid."' id='".$i."'>";
echo $line->title;
echo'<br>';
$result_array[$i] = $line->nid;
}
<input type='submit'>
?>
</form>
Then later on the code I'd like to store the values of the checked checkboxes only in a new array :
if (isset($_REQUEST['form_valid'])) //checking is form is submitted
{
foreach($result_array as $result)
{
if($result == $_REQUEST[$j]) <<<< ERROR
{
$final_array[$j] = $result;
}
}
}
Surprisingly, this code does not work at all.
The error message is "Notice : Undefined offset: 0", then offset 1 then 2 etc ...
The line where the message says theres an error is the marked one.
I really have no idea how to do this. Someone ? =)
Don't try to do it this way, this just makes it hard to process, just use a grouping name array: name="checkboxes[<?php echo $i; ?>]", then on the submission, all values that are checked should simply go to $_POST['checkboxes']. Here's the idea:
<!-- form -->
<form action="" method="POST">
<?php while($line = $results->fetch()): ?>
<input type="checkbox" class="checkbox" name="nid[<?php echo $line->nid; ?>]" value="<?php echo $line->nid; ?>" /><?php echo $line->title; ?><br/>
<?php endwhile; ?>
<input type="submit" name="submit" />
PHP that will process the form:
if(isset($_POST['submit'], $_POST['nid'])) {
$ids = $_POST['nid']; // all the selected ids are in here
// the rest of stuff that you want to do with it
}

How to write an update SQL statement to update multiple records

I have this code so far, which reads a simple table with 3 varchar fields:
<?php
//db connection code...
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM Sheet1";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<html><body><table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<form name="some form" action="editform.php" method="post">
<input type="checkbox" name="<?php echo $row['stickerID'] ?>" value=" <?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
echo "</table></body></html>";
echo " " ?>
<input type="submit" name="editWish" value="Edit">
</form>
<?php " ";
} else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
The database has 4 fields, 3 varchar and 1 int with current value of 0. I checked the page source code and confirmed each checkbox name is the stickerID. Now I will post this to the editform.php which I must create. What Im wondering is how should I write the update sql so that it takes into account each new value selected by the user in the form?
This is my idea, but how to I do it for every checkbox?
editform.php
<?php
//update multiple records
//UPDATE user_items SET stickerStatus = $_POST["stickerStatus"] WHERE stickerID = $_POST["stickerID"];
?>
First question: use mysql_fetch_assoc() instead of mysql_fetch_row(). That will return an associative array instead of an enumerated one.
Second question: read up on HTML forms and form handling.
The answer to the question in the comments:
// The <form> tag should only be echoed once.
echo '<form name="some form" action="editform.php" method="post">';
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<input type="hidden" name="status_<?php echo $row['stickerID"; ?>" value="0">
<input type="checkbox" name="status_<?php echo $row['stickerID'] ?>" value="<?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
// You need a submit button to send the form
echo '<input type="submit">';
// Close the <form> tag
echo '</form>';
Using a hidden input with the same name as the checkbox makes sure a value for the given input name is sent to the server. The value of a checkbox that's not checked will not be sent. In that case the hidden input will be used.
You can get the submitted values in editform.php as follows:
<?php
foreach ($_POST as $field => $value) {
if (strpos($field, 'status_')) {
// Using (int) makes sure it's cast to an integer, preventing SQL injections
$stickerID = (int) str_replace('status_', '', $field);
// Again, preventing SQL injections. If the status could be a string, then use mysql_real_escape_string()
$stickerStatus = (int) $value;
// Do something with the results
}
}
Do
print_r($row)
to find out exactly how your row arrays are constructed and work from there.
For your comparison operator, use
$row[3] === 0
instead of
$row[3] == 0
This will return true if both the value and data type match rather than just the value.
0 can mean the Boolean false aswell as the numeric value 0

If uncheck the check box delete row in my SQL table

Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}

Categories