I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}
Related
In the "User Setting" tab of my page, I want the user to determine which types of posts from a specific user. Here is the form:
<form method="post" action="" name="permitted_categories">
Select or deselect which types of Posts that you would like to see.
<p>
<?
$cat_query = mysqli_query($con, "SELECT permitcat FROM permitted WHERE username='$userLoggedIn' AND friendname='$username'")
?>
<label>
<input type="checkbox" name="categories[]" value="Life" id="Life" <? echo $checked;?>>
Life</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Politics" id="Politics" <? echo $checked;?>>
Politics</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Entertainment" id="Entertainment" <? echo $checked;?>>
Entertainment</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Food" id="Food" <? echo $checked;?>>
Food</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <? echo $checked;?>>
Business/Financial</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Fitness" id="Fitness" <? echo $checked;?>>
Fitness/Health</label>
<br>
<input type="submit" name="update_categories" id="update_categories">
<?
if(isset($_POST['update_categories'])) {
$permitted_categories = $_POST['categories'];
echo "You will only see the following categories from ". $profile_user_obj->getFirstAndLastName() .": ";
foreach ($permitted_categories as $permcat){
echo $permcat .", ";
}
$values = implode(", ", $permitted_categories);
$permit_query = mysqli_query($con, "INSERT INTO permitted (id, username, friendname, permitcat) VALUES('','$userLoggedIn', '$username', '$values')");
} ?>
</p>
</form>
What I am trying to do is automatically check the boxes where the corresponding values are found in an array.
I have tried several things, but cannot get the code to work.
this is pretty simple.
The HTML documentation:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
If you write "checked" at the end of the input Tag, this will be checked, as word says ;)
Another thing, don't mix tags:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
<label>Life</label>
And finally, your code will work if you make this at the beginning:
$checked = 'checked';
But this will check all boxes, you will need to check something, like this:
<?php $checked = 'checked'; ?>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <?php echo if($something == $otherThing) echo $checked;?> >
<input type="checkbox" name="categories[]" value="Life" id="Life" <?php if($something) { echo "checked"; }?>>
this may vary depending of the array content
here some examples
$assoc_array = [
"life" => "yes",
"food" => "no",
];
if($assoc_array['life'] == "yes"){ echo "checked"; }
$array = [
"life",
"food"
];
if (in_array("food", $array)) {
echo "checked";
}
$assoc_array_bool = [
"life" => "whatever",
"food" => "whatever"
];
if($assoc_array_bool['life']){ echo "checked"; }
// would not check the checkbox
// if you replaced $assoc_array_bool['life'] with $assoc_array_bool['sport']
this is radio button code
now what if radio button does not have a constant name how would i store the data in database because to store the data in database we will need a name of form attribute
$sql1="select * from questions where email='". $_SESSION['email'] ."'";
$row=mysqli_query($conn,$sql1);
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer4'];?>
if we know the name of radio button we can access it using
<input type="radio" value="<?php echo $result['answer4'];?>" name="name"><?php echo $result['answer4'];?>
$name=$_POST['name'];
but in the above code name of radio button is not fixed.questions is the table which consists of qid and questions with multiple options that is answer1,answer2 etc
i want to store the option select by user into database.for which i need to know the name of radio button
how should i use post in this case
$name=$_POST['what should go in here'];
You can get the radio button value along with question ID as:
Basic Example:
<?php
$array = array(1,2); // your Question ID array
?>
Your Form:
<form method="post" action="">
<?php
foreach ($array as $key => $qid) {
?>
<input type="radio" value="1" name="radio[<?=$qid?>]">
Answer 1
<input type="radio" value="2" name="radio[<?=$qid?>]">
Answer 2
<input type="radio" value="3" name="radio[<?=$qid?>]">
Answer 3
<input type="radio" value="4" name="radio[<?=$qid?>]">
Answer 4
<?php
echo "<br/>";
}
?>
<input type="submit" name="submit">
</form>
In PHP:
<?php
if(isset($_POST['submit'])) {
$query = array();
foreach ($_POST['radio'] as $key => $value) {
$query[] = "('$value','$key')";
}
$sql = "INSERT INTO table (answer,questionID) VALUES ";
$sql .= implode(",", $query);
echo $sql;
}
?>
In this example query look like:
INSERT INTO table (answer,questionID) VALUES ('2','1'),('3','2')
Few Suggestions:
- Your code is open for SQL Injection, you must need to prevent your code with SQL Attack and this reference will help you to understand: How can I prevent SQL injection in PHP?
- Make sure your column name and table name not having any conflict, currently, you are using same name for both.
Update with Your Code:
<?php
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer4'];?>
<?
}
?>
In PHP:
<?php
if(isset($_POST['submit'])) {
$query = array();
foreach ($_POST['radio'] as $key => $value) {
$query[] = "('$value','$key')";
}
$sql = "INSERT INTO table (answer,questionID) VALUES ";
$sql .= implode(",", $query);
echo $sql; // run this query in mysqli_query()
}
?>
Few More Instructions:
- Change the table name as per your table name
- Change the column name according to your column.
- Use INSERT query at once, no need to use it inside the loop.
Create an array at the end of while loop like this :
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer4'];?>
<? $names[] = $result['qid'];
}
if(isset($_POST['submit'])) {
for ($i=0; $i<count($names); $i++) {
if(isset($_POST[$names[$i]]) {
$rate = $_POST[$names[$i]];
$sql ="INSERT INTO answer (answer, qid) VALUES (".$rate.", ".$names[$i] .")";
mysqli_query($con, $sql);
}
}
}
?>
my code is,
$query3 = "SELECT * FROM db_exam_skip WHERE user='$session'";
$result3 = mysql_query($query3) or die(mysql_error());
$length3 = mysql_num_rows($result3);
while($rows3 = mysql_fetch_array($result3))
{
$query1 = "SELECT * FROM db_exam_questions WHERE id='$rows3[ques_id]'";
$result1 = mysql_query($query1) or die(mysql_error());
$length1 = mysql_num_rows($result1);
}
if(isset($_POST['next']))
{
if(isset($_SESSION['list']))
{
mysql_data_seek($result1,$_SESSION['list']);
}
else
{
$list = $_POST['list'];
mysql_data_seek($result1,$list);
}
}
<?php
while($rows1 = mysql_fetch_row($result1))
{
$start = $rows1[0];
$_SESSION['start'] = $start;
?>
<form action="" method="post">
<p style="font-size:20px;font-weight:bold"><?php echo $rows1[5]; ?></p>
<ul style="list-style-type:none">
<input type='hidden' name='number' value='<?php echo $_SESSION['order']++; ?>' />
<input type='hidden' name='list' value='<?php echo $_SESSION['list']++; ?>' />
<input type='hidden' name='ques_id' value='<?php echo $rows1[0]; ?>' />
<input type='hidden' name='correct' value='<?php echo $rows1[10]; ?>' />
<li><input type="radio" name="answer" value="1" /> <?php echo $rows1[6]; ?> <br><br>
<input type="radio" name="answer" value="2" /> <?php echo $rows1[7]; ?> <br><br>
<input type="radio" name="answer" value="3" /> <?php echo $rows1[8]; ?> <br><br>
<input type="radio" name="answer" value="4" /> <?php echo $rows1[9]; ?> <br></li>
</ul>
<input type="submit" class="button4" value="Next" name="next" />
</form>
<?php
break;
}
?>
my question is, after the first question is loaded, when i press next button to load the second question I am getting the below error.
Warning: mysql_data_seek(): Offset 2 is invalid for MySQL result index 8 (or the query data is unbuffered) in C:\wamp\www\Albert\ICAMS\start_skip_question.php on line 15
I have tried a lot to solve this error. But till now no success. Is there any method to solve. Any help will be appreciated.
Thank you.
I guess the result set is empty.I think query is returning empty set.
You will get this error if result set is empty
check the PHP DOCS
First check if you are getting ant rows from the result
if (mysqli_num_rows($sql) > 0)
{
}
I have this PHP/HTML Code that is selecting data from a MySQL Database:
<?php
$sql3="SELECT * from property_images where property_seq = '".$property["sequence"]."' ";
$rs3=mysql_query($sql3,$conn);
while($property_img=mysql_fetch_array($rs3))
{
?><tr>
<td colspan="2"><img src="http://domain.co.uk/img/property-images/<?php echo $property_img["image"]; ?>" width="80px" height="80px" /></td>
<td colspan="2"><input type="checkbox" name="image1" value="Y" <?php if($property_img["image1"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image2" value="Y" <?php if($property_img["image2"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image3" value="Y" <?php if($property_img["image3"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image4" value="Y" <?php if($property_img["image4"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image5" value="Y" <?php if($property_img["image5"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image6" value="Y" <?php if($property_img["image6"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image7" value="Y" <?php if($property_img["image7"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image8" value="Y" <?php if($property_img["image8"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image9" value="Y" <?php if($property_img["image9"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image10" value="Y" <?php if($property_img["image10"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image11" value="Y" <?php if($property_img["image11"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image12" value="Y" <?php if($property_img["image12"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image13" value="Y" <?php if($property_img["image13"] == 'Y') { echo 'checked="checked"'; } ?> /></td>
</tr><?php
}
?>
each row, has its own image with the columns image1 - image13
i want to update the table with the checkboxes that are checked and unchecked on the form update
how is this possible?
Thanks
If you mean that you want to update the $property_img["imagexx"] val on db depending on the user click on the checkbox you must use ajax.
Fire an event on triggering each checkbox and send the value to a php page that update the php.
Jquery Ajax function can help you on this task.
L
name all your checkboxes images[]
<input type="checkbox" name="images[]" value="1" />
<input type="checkbox" name="images[]" value="2" />
<input type="checkbox" name="images[]" value="3" />
<input type="checkbox" name="images[]" value="4" />
You can then update with PHP :
<?php
$q = "UPDATE property_images SET";
foreach($_POST["images"] as $image) {
$q .= " image" . $image ." = 'Y', ";
}
$q .= " property_seq = '".$property["sequence"]."' WHERE property_seq = '".$property["sequence"]."'";
mysql_query($q);
?>
First of all, mysql_ functions are deprecated, please google mysqli_ or PDO, mysql_ won't be supported on future versions, and is unsafe, etc
Your html output could be much simpler with a loop, also have an eye on putting the sequence number on a hidden field or something first:
<?php
$sql3="SELECT * from property_images where property_seq = '".$property["sequence"]."' ";
$rs3=mysql_query($sql3,$conn);
while($property_img=mysql_fetch_array($rs3)){
?>
<tr>
<td colspan="2"><img src="http://domain.co.uk/img/property-images/<?php echo $property_img["image"]; ?>" width="80px" height="80px" /></td>
<!-- THIS IS VERY IMPORTANT: send the sequence or ID through a hidden field, to know which row you are gonna update later-->
<input type="hidden" name="sequence" value="<?php echo $property_img['sequence']; ?>"/>
<td colspan="2">
<?php for($i = 1; $i <= 13; $i++): ?>
<input type="checkbox" name="images[]>" value="<?php echo $i; ?>" <?php if($property_img["image$i"] == 'Y') { echo 'checked="checked"'; } ?> />
<?php endfor ?>
</td>
</tr>
<?php
}
?>
Then this is the next page where the update is done, have a good look at the comments:
<?php
//Handle as you want the situation when there are no images selected instead of using an exit(), I used it here just for the quickness;
if(count($_POST['images'] < 1) exit('no images where selected to update');
$images = array();
for($i = 1; $i <= 13; $i++){
$string = "image$i = ";
if(in_array($i, $_POST['images'])){
$string .= "'Y'"; //notice the double quoting here, it's important
} else {
//This updates the table so if it was checked when loaded, but unchecked by the user, this makes the change!
$string .= "'N'";
}
}
//This creates a string like: image1 = 'Y', images2 = 'N', etc...
$images = implode(', ', $images );
//try to sanitize the query first ... I won't cos am just showing you your question xD
$sql = "UPDATE property_images SET $images WHERE property_seq = " . mysql_real_escape_string($_POST[sequence]) . ";
mysql_query($sql,$conn);
?>
I have the following html code:
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
And the following PHP script:
//arrayplay.php
foreach ($_POST['todelete'] as $id)
{
echo $id . "<br/>";
}
?>
It is supposed to echo out each element value but instead I get an error. I am getting really frustrated. If I use:
<form method="post" action="arrayplay.php">
<?php
$dbc= //connection
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
echo $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove" />
</form>
It works perfectly fine! Why? The first (hard coded html) holds the exact same value as the one that retrieves them from the database. I am having a real hard time understanding retrieving values from an array with $_POST. Why does name=foo[] create an array? Is it an associative or numeric array? I'm sorry for all of the questions, I'm just really ready to pull my hair out.
if you just named the input foo it would only get one value. because square brackets are commonly used for arrays, foo[] is how in the html form, you indicate an array. of course on the PHP side you just call it foo as you are aware from your working example.
I've tested this and it should work:
<?php
if ($_POST['delete']) {
foreach ($_POST['todelete'] as $id) {
echo $id.' selected<br />';
}
}
?>
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
If you're still having troubles, you can try:
<?php
if ($_POST['delete']) {
for ($i = 0; $i < 4; $i++) {
if (isset($_POST['todelete'][$i])) {
echo $_POST['todelete'][$i].' selected<br />';
}
}
}
?>