Suppose that I have the code php as below:
<?php
include("connectdb.php");
$check1 = "";
$check2 = "";
$check3 = "";
$check4 = "";
$check5 = "";
$query = "SELECT * FROM tblworkfaire";
$res = mysql_query($query) or die(mysql_error());
if($res){
while($data = mysql_fetch_array($res)){
if($data['1.DesTechnique'] == 1){
$check1 = "CHECKED";
echo $check1;
}
else if($data['1.DesTechnique'] == 2){
$check2 = " CHECKED";
}
else if($data['1.DesTechnique'] == 3){
$check3 = "CHECKED";
}
else if($data['1.DesTechnique'] == 4){
$check4 = "CHECKED";
}
else if($data['1.DesTechnique'] == 5){
$check5 = "CHECKED";
}
}
}
else{
echo "Fail";
}
?>
And Html code:
<form action="word2html.php" method="post">
<input type="radio" name="number1" value="1" checked="<? $check1; ?>">
</b><b>
<input name="number1" type="radio" value="2" checked="<? $check2; ?>">
</b><b>
<input name="number1" type="radio" value="3" checked="<? $check3; ?>">
</b><b>
<input name="number1" type="radio" value="4" checked="<? $check4; ?>">
</b><b>
<input name="number1" type="radio" value="5" checked="<? $check5; ?>">
</b>
What I need:
I have stored the radio box value in database,if I select value from database equal 1,it will check the radio box that have the value equal 1.
Problem:
I can only select value of radio box from database and it dose not work.How do I fix this? Anyone help me please, Thanks.
That's some rather horrible code.
First problem: You're doing a while() loop to fetch results from your query. If you're fetching multiple rows of data, the you'll be setting all or some of those $checkX variables, yet not actually doing anyhing with them during that particular loop iteration. Assuming you fetch enough rows, eventually ALL of those variables will be checked and you end up selecting all of your radio buttons.
If you're expecting only a single row of data, then the while() is simply cargo cult programming.
Second problem. You've repeated a lot of code in there, and define a lot of variables, for something that could be done far easier/cleaner with a loop. e.g.
for ($i = 1; $i <= 5; $i++) {
$checked = ($data['1.DesTechnique'] == $i) ? ' checked="checked"' : '';
echo <<<EOL
<input name="number1" type="radio" value="$i"$checked>$i<br />
EOL;
}
No $checkX variables, no repeated inputs. just a nice loop doing the output for you.
You need to output your variables.
<input type="radio" name="number1" value="1" checked="<?php echo $check1; ?>">
Related
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.
This question already has answers here:
Get checked and unchecked checkboxes value
(3 answers)
Closed 8 years ago.
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[<?php echo $group['id']; ?>]" <?php echo $checked; ?>>
<?php
}
?>
Will output:
<form action="test.php" method="post">
<input type="checkbox" name="delete_user[1]">
<input type="checkbox" name="delete_user[2]">
<input type="checkbox" name="delete_user[3]">
<input type="checkbox" name="delete_user[4]" checked="checked">
<input type="submit" name="save_action" value="Save">
</form>
And when I check inputs as wanted, then this will process input.
<?php
if(isset($_POST['save_action']) {
if (empty($_POST['delete_user'])) {
$_POST['delete_user'] = array();
}
foreach($_POST['delete_user'] as $del) {
is_checked($del); //#todo
}
}
?>
I am looking for way to check if check-box is checked and return proper value ( Y or N ). In this point I declared is_checked() function for this purpose.
I would do it like this:
<form action="test.php" method="post">
<input type="checkbox" name="delete_user[]" value="1">
<input type="checkbox" name="delete_user[]" value="2">
<input type="checkbox" name="delete_user[]" value="3">
<input type="checkbox" name="delete_user[]" value="4" checked="checked">
<input type="submit" name="save_action" value="Save">
</form>
Now in PHP you can loop over the $_POST['delete_user'] and it will contain the values of the selected items.
foreach($_POST['delete_user'] as $item)
{
// code to delete $item
}
As the comments already mentioned, only the checked checkboxes will be set
So you either have to take the index as ID or add a val to each input element.
The latter would probably be cleaner (in my opinion)
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[]" <?php echo $checked; ?> value="<?php echo $group['id'];?>">
<?php
}
?>
And the code which does something with the inputs:
<?php
if(isset($_POST['save_action']) {
if (empty($_POST['delete_user'])) {
$_POST['delete_user'] = array();
}
foreach($_POST['delete_user'] as $del) {
// do something with $del - the id
}
}
?>
Use the checkbox name just as an array and then give the id as value. See the below code.
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[]" value="<?php echo $group['id']; ?>" <?php echo $checked; ?>>
<?php
}
?>
Then on the action page place this code
<?php
foreach($_POST['delete_user'] as $del) {
is_checked($del); //#todo
}
}
?>
This will work fine.
I'm relatively new to PHP and have been working on a basic survey as a practice project.
The user logs in, answers the questions and the data is sent to the database. So far so good.
However, since the only thing that the login is set up for is to do the survey, I want them to be able to go back and change their answers at any time.
I've set it up so that it checks if the user has already filled in the info on the database, and edits values rather than adding new row if they've filled it in before.
However, I now want them to be able to see the choices that they made and edit them.
I know how to get the data back and echo it to the page, what I don't know how to do is get it to display the form with the default values set at the users previous selections.
Apologies for any display problems, its being a bit erratic!
so for example:
<?php if(!isset($_SESSION['username'])){
// are logged in
header("location:login.php");
} ?>
<form name="questionnaire" action="submit_survey.php" method="post">
<input name="Q1" type="radio" method="post" value="1">1
<input name="Q1" type="radio" method="post" value="2">2
<input name="Q1" type="radio" method="post" value="3">3
<input name="Q1" type="radio" method="post" value="4">4
<input name="Q2" type="radio" method="post" value="1">1
<input name="Q2" type="radio" method="post" value="2">2
<input name="Q2" type="radio" method="post" value="3">3
<input name="Q2" type="radio" method="post" value="4">4
</form>
PHP sending to database:
include('db_login2.php');
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
if(mysqli_connect_errno($con)) {
echo "failed to connect" . mysql_connect_error();
}else {
$username = $_SESSION['username'];
//Question 1.1
$Q1 = $_POST['Q1'];
$Q2 = $_POST['Q2'];
//INJECTION PREVENTION (Not shown)
$resulting = mysqli_query($con, "SELECT username FROM users WHERE username='$username'");
$counting = mysqli_num_rows($resulting);
if($counting != 0){
mysqli_query($con,"UPDATE users SET Public_Services='$Q1', Politicians='$Q2'
WHERE username='$username'");
$_SESSION['completed'] = true;
header("location:login.php");
mysqli_close($con);
} else {
$sql= "INSERT INTO users(username, Public_Services, Politicians)
VALUES ('$username','$Q1', '$Q2')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//if it works
$_SESSION['completed'] = true;
header("location:loggedin.php");
mysqli_close($con);
}
}
?>
PHP for getting data back from database
include('db_login2.php');
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
if(mysqli_connect_errno($con)) {
echo "failed to connect" . mysql_connect_error();
}else {
$username = $_SESSION['username'];
$result = mysqli_query($con,"SELECT * FROM users WHERE username='$username'");
echo $row = mysqli_fetch_array($result);
mysqli_close($con);
}
?>
I was wondering if it was possible to do something like having inline php in the html form which comes to life depending on the value of the user's original selection.
Any thoughts?
Thanks for any help!
To populate the survey with the users previous answers, you would us the $row = mysqli_fetch_array($result);
<?php
... // all your other code
$row = mysqli_fetch_array($result);
?>
<form name="questionnaire" action="submit_survey.php" method="post">
<input name="Q1" type="radio" value="1" <?php if($row['Public_Services'] == 1) echo 'checked="checked"'?>>1
<input name="Q1" type="radio" value="2" <?php if($row['Public_Services'] == 2) echo 'checked="checked"'?>>2
<input name="Q1" type="radio" value="3" <?php if($row['Public_Services'] == 3) echo 'checked="checked"'?>>3
<input name="Q1" type="radio" value="4" <?php if($row['Public_Services'] == 4) echo 'checked="checked"'?>>4
<input name="Q2" type="radio" value="1" <?php if($row['Politicians'] == 1) echo 'checked="checked"'?>>1
<input name="Q2" type="radio" value="2" <?php if($row['Politicians'] == 2) echo 'checked="checked"'?>>2
<input name="Q2" type="radio" value="3" <?php if($row['Politicians'] == 3) echo 'checked="checked"'?>>3
<input name="Q2" type="radio" value="4" <?php if($row['Politicians'] == 4) echo 'checked="checked"'?>>4
</form>
or using a php for loop
<?php
... // all your other code
$row = mysqli_fetch_array($result);
echo '<form name="questionnaire" action="submit_survey.php" method="post">';
for($i=1;$i<=4;$i++){
echo '<input name="Q1" type="radio" value="'.$i.'"';
if($row['Public_Services'] == $i) echo 'checked="checked"';
echo " />".$i."<br />\n";
}
echo "<br />\n";
for($i=1;$i<=4;$i++){
echo '<input name="Q2" type="radio" value="'.$i.'"';
if($row['Politicians'] == $i) echo 'checked="checked"';
echo " />".$i."<br />\n";
}
echo "</form>";
?>
You could either output the form's results as values in the HTML itself, or you could create a small Javascript snippet via PHP that will set the appropriate values once the form is loaded. The second method is much cleaner, but your clients will need to support Javascript for this to work. This isn't usually a problem, unless they've explicitly disabled Javascript, in which case the page just won't show the form data.
Using jQuery, you could do something like:
$(function() {
<?php
if (isset($foo)) { // foo is a value from your database
echo '$("#fooField").val("' . $foo . '")';
}
// ....more fields here
?>
}
Thus, the aforementioned code will output a jQuery code on load which will set the appropriate values for all of the form elements
You can have tags inside the html and echo the form based on the values.
Or you simply echo every line.
Edit: You might have a look at this: http://php.net/manual/en/control-structures.alternative-syntax.php
OK this is my script:-
<form action="results.php" method="post">
<?php mysql_select_db($database, $databasename) or die("Opps some things went wrong");
$sqlQueryTestDisplay = mysql_query("SELECT * FROM questions WHERE test_id='$testtaken_id' ORDER BY question_id ASC");
$i = 0;
while($DisplayItems = mysql_fetch_array($sqlQueryTestDisplay))
{
$i = $i + 1;
$question_id = $DisplayItems['question_id'];
$question = $DisplayItems['question'];
$opta = $DisplayItems['opta'];
$optb = $DisplayItems['optb'];
$optc = $DisplayItems['optc'];
$optd = $DisplayItems['optd'];
$answer[$i] = $DisplayItems['answer'];
$thisAnswer = $answer[$i];
echo '<li>'.$question.'</li>';
echo '<p>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_0" />'.$opta.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_1" />'.$optb.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_2" />'.$optc.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_3" />'.$optd.'</label>';
echo '<input name="ans'.$i.'" type="hidden" value="'.$thisAnswer.'" />';
echo '</p>';
}
echo '<input name="total_questions" type="hidden" value="'.$i.'" />';
echo '<input name="test_id" type="hidden" value="'.$TestID.'" />';
?>
<input name="submittest" type="submit" />
</form>
As you can see i am using array to store values in different fields. Now on the next page i.e on my result.php page I am writing this:-
<?php
if(isset($_POST['submittest']))
{
global $ans1;
$TotalQuestions = $_POST['total_questions'];
$TestID = $_POST['test_id'];
$TestResult = 0;
for ($i=1; $i<=$TotalQuestions; $i++)
{
$ansValue = 'ans'.$i;
$optansValue = 'optans'.$i;
$ans = $_POST[$ansValue];
$optans = $_POST[$optansValue];
if ($ans == $optans)
{
$TestResult = $TestResult + 1;
}
}
$st_id = $row_Recordset1['id'];
mysql_select_db($database, $databasename) or die("Opps some things went wrong");
$sqlQueryInsertResult = mysql_query("INSERT INTO results (student_id, test_id, test_result) VALUES ('$st_id', '$TestID', '$TestResult')");
header('location:results.php');
}
?>
Now my script is not reading ans1, ans2.....and so on AND even quesans1, quesans2.....and so on.
I think problem is in the way i am calling the array using the $_POST method.
Is the syntax correct, how can i FIX it... Please help :|
All of your radio buttons are returning "radio" as their value. Make them return the answer and you should be OK
Change your radio definitions to:
'<INPUT type="radio" name="optans'.$i.'" value="'.$opta.'" >'.$opta.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optb.'" >'.$optb.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optc.'" >'.$optc.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optd.'" >'.$optd.'</INPUT>'
Might be worth not putting the answer onto the page as a hidden field - makes a quiz quite easy. Do another SQL query to check the answers when they come back
Use some more loops to display the radio buttons and you can shorten your code a bit.
0Change your test options to this:
echo '<label><input type="radio" name="optans'.$i.'[]" value="1" id="RadioGroup'.$i.'_0" />'.$opta.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="2" id="RadioGroup'.$i.'_1" />'.$optb.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="3" id="RadioGroup'.$i.'_2" />'.$optc.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="4" id="RadioGroup'.$i.'_3" />'.$optd.'</label>';
and your processor to this:
<?php
if(isset($_POST['submittest']))
{
global $ans1;
$TotalQuestions = $_POST['total_questions'];
$TestID = $_POST['test_id'];
$TestResult = 0;
for ($i=1; $i<=$TotalQuestions; $i++)
{
$ans = $_POST['ans'.$i];
$optans = $_POST['optans'.$i];
for ($j=0;$j<count($optans);$j++) {
if ($optans[$j]==$ans) {
$TestResult = $TestResult + 1;
}
}
}
This is a very insecure way to compare test answers. Someone could easily View Source and see the correct answers. You should validate the test answers after the $_POST
I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.