Can't see input radio checked, but it is in code - php

i'm stuck in a weird problem with a page
<table class='table'>
<?
print_r($selected_working_time);
// it print a previous selection of working time. for example:
// Array ( [0] => 5 [1] => 6 [2] => 4 [3] => 7 [4] => 9 [5] => 8 )
$query="SELECT Working_time_code, Working_time_description
FROM Working_time
ORDER BY Working_time_description";
// a table with a working_time code and his description. for example:
// 1 - Part-time; 2 - Full-time, ..., 9 - 10:00 - 16:00
if($stmt = $connection->prepare($query)) {
$stmt->execute();
while($all_working_time = $stmt->fetch(PDO::FETCH_ASSOC)) {
$desc = trim($all_working_time['Working_time_description']);
$code = $all_working_time['Working_time_code'];
echo"<tr><td>$desc</td>";
if(in_array($code, $selected_working_time)) { // if code is in my selection, YES checkbox is checked, else NO checkbox is checked.
echo "<td><label class='radio-inline'><input type='radio' name='$codice' value='Y' checked />YES</label>
<label class='radio-inline'><input type='radio' name='$codice' value='N' />NO</label></td>";
}
else {
echo "<td><label class='radio-inline'><input type='radio' name='$codice' value='Y' />YES</label>
<label class='radio-inline'><input type='radio' name='$codice' value='N' checked />NO</label></td>";
}
echo"</tr>";
}
}
?>
</table>
This code works fine, because when i show source code of my generated page i see correctly checked checkbox, but no one of them is really checked.
Where is the problem? It's like a visualization problem, it isn't working with firefox and chrome.
Thank you.

Related

PHP MYSQL checkbox search

I am working on a checkbox search. I'm new to PHP. I would appreciate it if someone could help me. Basically the user checks the options required, hits submit and results matching the checkbox options is displayed. The checkboxes have a value of M for Male and F for Female which matches the data in the MYSQL table.
So if a user checks checkbox 'Male' (see code below) all data with 'Male' that have a value of 'M' in the MYSQL table are returned. And any checkboxes not checked should simply be ignored as the user is only interested in the option 'Male' being 'M' (true).
To sum up I only need the search to take into account checkboxes that have been checked and echo which users that has been selected(more like filtering) through PHP.Any help appreciated. Thanks
the table looks like this :
id name address gender race
-------------------------------------------
1. 1 Lee NY M French
2. 2 James LA M Colombian
3. 3 Kashi JAPAN F Japanese
and i have a form with checkboxes like this :
<form action="shortlist.php" method="post">
<label for="sel1">Gender:</label>
Male:<input name="keyword[]" type="checkbox" value="M" />
Female:<input name="keyword[]" type="checkbox" value="F" />
<button name = "myBtn" type="submit" class="btn btn- default">Search</button>
</form>
SQL :
$sql="SELECT name, address,gender,race FROM talent1 WHERE gender = $gender'";
I'm suppose to echo something like this :
echo "<table width='100%'>\n";
//if (mysqli_num_rows($result) > 0){
//$row=mysqli_fetch_assoc($result);
//$muchneededid = $row["talent_id"];
while ($row=mysqli_fetch_assoc($result))
echo'<tr>'."\n";
echo '<tr>';
echo '<th>Name</th>';
echo '<th>Address</th>';
echo '<th>Gender</th>';
echo '</tr>';
echo "<td>{$row["name"]}</td>\n" . "<td>{$row["address"]}</td>\n" . "<td>{$row["gender"]}</td>\n";
echo '</tr>'."\n";
echo "</table>\n";
}
else
{
echo "0 results";
}
mysqli_close($conn);
}
given the information we've got it would be something like this:
<?php
//$_POST['keyword'] = array("M", "F");
$sql_addon = ''; // EDIT: this was one line below first, which of course created an 'undefined' error.
if(isset($_POST['keyword'])) {
foreach($_POST['keyword'] as $k => $val) {
$sql_addon.= " OR gender='$val'";
}
}
$sql="SELECT name, address,gender,race FROM talent1 WHERE 1=1 ";
if($sql_addon) {
$sql .= " AND (1=2 ".$sql_addon.")";
}
echo $sql;
// SELECT name, address,gender,race FROM talent1 WHERE 1=1 AND (1=2 OR gender=M OR gender=F)
?>
Those 1=1 and 1=2 might look silly, but it's (IMHO) the easiest way to generate that sql. 1=2 is there to create a falsy value, so that no records will be shown if none of the options are clicked.

Comparing only the selected value in loop to avoid error message

I am trying to build a basic quiz system.The following code shows how user choose the answer using radio butto and the getresult.php compares the radio input value with answer column. In my database there is a question, opt1, opt2, opt3, opt4, and answer columns.
<form method="POST" action="getresult.php">
<label>Enter Your Name:</label><br>
<input type="text" name="name"><br><br>
<?php
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
echo "<form method='POST' action='getresult.php'>";
while($myrow = $result->fetch_assoc())
{
echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt4'].">";
echo $myrow['opt4'];
echo "<br><br>";
}?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">
// getresult.php
<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$submit=isset($_POST['submit']);
$count=0;
if($submit)
{
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
echo "Hello ";
echo $_POST['name'];
echo "<br>";
echo "You scored ";
echo "$count";
}
Everything is correct, but if I do not select a radio button from a question, i.e if I leave the question it displays undefined offset error which is obvious but how can I not display that. OR how can I compare only chosen options?
You should try array_key_exists() like this:
if(array_key_exists($myrow['id'], $mycheck)
&& array_key_exists('answer', $myrow)
&& $mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
Or better yet, request your answers from database based on validated rows.
When the form is submitted, the chosen values are passed as (for example):
mycheck[1]=2
mycheck[2]=3
mycheck[3]=1
mycheck[4]=2
...etc. Now if you leave one question unanswered, let's say question 2, then no value will be submitted to the server for that question, so the submitted values could be something like this:
mycheck[1]=2
mycheck[3]=1
mycheck[4]=2
When PHP stores this in $_POST[], it will be an associative array:
$_POST['mycheck'] === array(
'1' => 2,
'3' => 1,
'4' => 2
)
With extract($_POST) you get the following value for $mycheck:
$mycheck === array(
'1' => 2,
'3' => 1,
'4' => 2
)
Now the following loop in your code will still go through all questions:
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
But (in the example) the check for question 2 will fail, because $myrow['id'] will equal 2, while $mycheck[2] does not exist. This produces the undefined offset error.
As an unanswered question obviously should not increase the count, you could solve this issue as follows: first test if the question was answered (does $mycheck have an entry for it?), and only if that is the case, retrieve the answer from that entry:
while($myrow = $result->fetch_assoc())
{
$id = myrow['id'];
if(array_key_exists($id, $mycheck) && $mycheck[$id]==$myrow['answer'])
{
$count=$count+1;
}
}
For the above extra test you can use array_key_exists, or isset.
A bit rusted on PHP, but ...
Have you tried using the isset() function? Or changing the error reporting level appropriately?
http://php.net/manual/pt_BR/function.error-reporting.php
Why don't you create a new radio button "Don't know " which would be initially checked
<input type="radio" name="" checked>
So by default that button will be checked.

Trying to pass checkbox and dropdown results to a php file

I have made a form with checkboxes and 2 dropdowns populated by mysql.
I can get both to work on separate pages but cannot merge together in one form.
Here is my form code
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("test") or die (mysql_error());
$query = "SELECT name from aa";
$result = mysql_query($query);
?>
<form method = "post" action = "check2code.php">
<select name = "select1">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['name']; ?>"> <?php echo $line ['name']; ?></option>
<?php
}
?>
</select>
<input type="submit" value="Submit" />
</form>
Here is the php im sending to
<?php
print_r($_POST['day']);
print_r ($_POST['select1']);
?>
the error i get is
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 8 [5] => 9 [6] => 10 [7] => 16 )
Notice: Undefined index: select1 in /opt/lampp/htdocs/test/check2code.php on line 5
so the check box is fine the dropdown is not.
Maybe that no option is selected? The var $_POST['select1'] is only initialized if there is at least one option selected. Just try to select an option before you send the forms data to the server.
Try with mysql_fetch_assoc, not mysql_fetch_array.

multiple post values in for each php

So I am working with some checkboxes that are populated from a db table. Which looks like this.
<form action="" method="post">
<?php
foreach ($chores as $retrieved_search){
?>
<tr>
<td>
<?php echo "<input type='checkbox' id=".$retrieved_search->id." value=".$retrieved_search->image." name='chores[]'>$retrieved_search->name";?>
<?php echo "<input type='text' value='$retrieved_search->name' id='optionName' name='optionName[]' />"?>
</td>
</tr>
<?php
}
?>
</form>
I am trying to figure out a way that I can get that value from the checkbox which I am currently doing and works fine. The value from the checkbox is an image URL.
I also need to get the name associated with the checkbox so I added another input field that is populating the name of the checkbox which I will then hide.
So this is my php statement that is getting the post value from the checkbox but how can I also get the value from the input field for the same insert statement?
<?php
if(isset($_POST['saveOptions'])) {
global $wpdb;
$table_name = $wpdb->prefix . "chartUsersOptions";
$user_ID = get_current_user_id();
$typeChore = "chore";
$typeBehavior = "behavior";
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores) {
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'type' => $typeChore,
));
}
}
$msg = "Saved now redirect to 3rd step";
echo $msg;
}
else{
.............
}
?>
EDIT:
Based on a suggestion This worked.
<?php
foreach ($chores as $retrieved_search){
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
}
?>
And This
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'optionName' => $text_input_value,
'type' => $typeChore,
));
}
}
But optionName is still inserting blank.
I'm not sure what the exact problem is, but my guess is that your checkboxes don't match your input boxes. That is because unchecked checkboxes do not get sent to the server, so you probably end up with an checkboxes array that is smaller than the input boxes array.
You should change your html so that a checkbox-array-key always matches an input-array-key, so something like:
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
Also note that ID's need to be unique so I removed them but that is probably not related to your problem.
Edit: To get the value of the text box after making the above changed, you can do:
if (isset($_POST['chores'])) {
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
// and the rest of your code
Instead of
foreach ($_POST['chores'] as $chores) {
you want
foreach ($_POST['chores'] as $id=>$chores) {
Then you can access
optionName[$id]
in your loop.

Save multiple selected checkboxes in the database

i hope someone can help me. i have 4 checkboxes i want to save it in one string in my database,for example you only choose 2 or 3 checkboxes options.. the selected values only will save in one field of my database..
<tr>
<td><label>Plan Description:</label></td>
</table>
<?php
$des_query=mysql_query("SELECT * FROM addons;") or die ("Note: ". mysql_error());
?>
<?php
while($desc = mysql_fetch_array($des_query))
{
echo "<input type='checkbox' name='addons[]' value=".$desc['id'].">". $desc['name']."</input><br/>";
}
?>
</tr>
$insStr = '';
foreach($_POST['addons'] as $val){ $insStr .=$val.","; }
mysql_query("INSERT INTO promos (promo) VALUES ( '$insStr' )");
You can use serialize() method
example
$arr = Array ( [0] => 1 [1] => 2 [2] => 3);
$str = serialize($arr);
After retrieving from database use unserialize() method
You can take advantage of PHP built-in function named implode
Example
$checkboxValue implode(',',$_POST['addons']);
Try like this
if(!empty($_POST['addons'])) { $addons_string="";foreach($_POST['addons'] as $addon){$addons_string.=$addon.","; } }
test.php
<form name="test" action="test1.php" method="get">
<?php
for($i=0; $i<9;$i++){
echo "<input type='checkbox' name=a[] value=$i>$i<br>";
}
?>
<input type="submit" value="Submit">
</form>
and test1.php
<?php
foreach($_GET['a'] as $check) {
echo $check;
//SAVE VALUES TO DATABASE
}
?>
Hope it will help you

Categories