Set mysql values from radio buttons in html form - php

I want two radio buttons on a webpage (written in php) representing "yes" and "no". When I load the page I want it to fetch a value from a mysql db and set the corresponding radio button. And when I click on the other button, I want it to update the database and reload the page.
I'm trying to do this with a simple html form, but no luck. The code I have so far (that is not working at all :( is:
if (!isset($_POST['submit'])) {
$sql = "SELECT challenge_me FROM contestants WHERE id=$id";
$res = (mysql_fetch_assoc(mysql_query($sql, $db)));
$challenge_me = $res["challenge_me"];
}else{
$sql = "UPDATE contestants SET challenge_me='" . $_POST['YesNo'] . "' WHERE id='$id'";
if(!mysql_query($sql, $db))
echo mysql_error(), "<br/>Query '$sql'";
$challenge_me = $_POST['YesNo'];
}
echo'<form method="post" action="' . $PHP_SELF . '">';
echo '<input type="hidden" name="submit" value="submit">';
if($challenge_me == 1){
echo'<input type="radio" name="YesNo" value="1" onClick="this.form.submit();" checked>Yes ';
echo'<input type="radio" name="YesNo" value="0" onClick="this.form.submit();">No ';
}else{
echo'<input type="radio" name="YesNo" value="1" onClick="this.form.submit();">Yes ';
echo'<input type="radio" name="YesNo" value="0" onClick="this.form.submit();" checked>No ';
}
echo'</form>';

Your script doesnt seem to define $id, where does $id get its value from? That could be the source of your problem. Your script might not be passing any value in $id

Related

php: getting a variable (user selection from radio button) to another file

I have a list of items in one file (fruit.php):
<form action="delete_items.php" method="post">
<input type="radio" value="apple" name="fruit">Apple<br>
<input type="radio" value="pear" name="fruit">Pear<br>
<input type="radio" value="banana" name="fruit">Banana<br>
<input type="submit" value="delete" name="deleteButton"><br>
</form>
In the delete_items.php, I have a variable that stores the selection:
<?php
$selection = $_POST["fruit"];
echo "are you sure you want to delete it?";
echo '<form action="delete_confirmation.php" method="post"><br>';
echo '<input type="submit" name="deleteYes" value="Yes"><br>';
echo '<input type="submit" name="deleteNo" value="No"><br>';
echo '</form>';
?>
Than in the confirmation file (delete_confirmation.php):
<?php
include 'delete_items.php';
if($_POST["deleteYes"]){
$query = 'DELETE FROM databaseName WHERE fruitName="' . $selection . '"';
$result = mysqli_query($connection, $query);
if(!$result){
die("Delete after check query failed!");
} else {
echo "Delete after check query success!";
}
} elseif($_POST["deleteNo"]){
echo "The course was not deleted!";
}
?>
But the varibale $selection in the delete_confirmation.php file is always null even though i included the delete_items.php file (when i echo it, nothing is shown). Is there a way to pass the selection variable from delete_items.php to the delete_confirmation.php file?

Display name of radio button selection upon form submit

I have a form in html with several fields, one of which is a radio button.When I submit the form into a php page I want to display the contents of each field and the name of the radio button selection. However the radio button doesn't display the name property but echoes "on" when selected and nothing when not, what can I do to show the name of the selection?
this is the html page
<html>
<body>
<form action="confirmdata.php" method="post">
Name <input type="text" name="name"><br><br>
Gender <input type="radio" name="gender" value="Male">Male<input type="radio" name="gender" value="Female">Female<br><br>
Email <input type="text" name="email"><br><br>
Inform email <input type="checkbox" name="inform"><br><br>
<input type="submit">
</form>
</body>
</html>
and this is the php page
<html>
<body>
<?php
foreach($_POST as $data){
echo $data; ?>
<br>
<?php
}
?>
Return to registration form
</body>
</html>
I'm guessing that, maybe this might help you to figure it out:
$html = '';
foreach ($_POST as $data) {
$html .= '<input type="radio" name="gender" value="' . $data . '"> ' . $data . '<br>';
}
echo $html;
It seems you have your form values in the $data. When you loop through it, it will fill the values back in the input radio elements that you have. You might also need to add the keys to name attributes:
$html = '';
foreach ($_POST as $key => $data) {
$html .= '<input type="radio" name="' . $key . '" value="' . $data . '"> ' . $data . '<br>';
}
echo $html;
I think you want display the selected values after submit the form. so $_POST['gender'] is holding the value either 'Male' or 'Female', so after submit the form add condition to check $gender is male or female then use checked attribute inside a radio button tag.
Please follow the below simple steps.
$gender = $_POST['gender'];
if ($gender == 'Male') {
?>
<input type="radio" name="gender" value="Male" checked>Male
<?php
}
else {
?> <input type="radio" name="gender" value="Female" checked>Female<br><br>
<?php
}

checkbox could not uncheck php

I have written a code to save the check values of checkboxes to database.
check condition is working fine as in the checked values are saving to database when submit and it keeps checked when submit and refresh.
But when it uncheck and submit then refresh the page the checkbox still keeps remained checked. It won't saved the status of unchecked.
I include a chunk code which is related to this issue. If anyone can get the issue that'd be great.
echo "<form action='' class='' method='post'><tr>";
$sql_stamp = "SELECT check_list FROM time_stamps WHERE nJobNumber=".$nJobNumber;
$query_stamp = $conn->prepare($sql_stamp);
$query_stamp->execute();
$numRows = $query_stamp->rowCount();
if($numRows > 0){
$row_stamp = $query_stamp->fetch(PDO::FETCH_ASSOC);
$checkboxes = explode(',',$row_stamp['check_list']);
echo ' <td><center> <input type="checkbox" name="check_list[]" value="shop_drawing" '.(in_array( "shop_drawing",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="site_measure" '.(in_array( "site_measure",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="shop_drawings_approved" '.(in_array( "shop_drawings_approved",$checkboxes) ? "checked =checked" : "").'></td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch" '.(in_array( "batch",$checkboxes) ? "checked=checked" : "").'></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo ' <td><center> <input type="submit" name="submit" value="Submit"/> </td>';
echo '<td><input type="hidden" name="job_number[result]" value="'."true".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}else{
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawing"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="site_measure"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawings_approved"> </td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch"></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo "<td><center> <input type='submit' name='submit' value='submit'></td>";
echo '<td><input type="hidden" name="job_number[result]" value="'."false".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}
echo "</tr> </form>";
}
echo "</tbody> </table>";
?>
Insert values to database:
if(isset($_POST['submit']))
{
$checkbox = $_POST["check_list"];
$job_number = $_POST["job_number"];
$batch_no = $_POST["batch_no"];
date_default_timezone_set('Australia');
$date_time = date("Y-m-d h:i:sa");
//$username = "$SESSION[userid]";
if($job_number["result"] == "true"){
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
}
else{
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('INSERT INTO time_stamps (nJobNumber,time_date,username,batch_no,check_list) VALUES (?,?,?,?,?)');
$stmt->bind_param('issss',$job_number["number"],$date_time,$username,$batch_no,$checkboxes);
$stmt->execute();
}
}
}
Basically, What's my requirement is when a user uncheck a 'checked' checkbox it should be unchecked when submit the form (after a refresh). But in my case it keeps checked.
Neither of your queries will execute if the user submits a form with no checkboxes checked. While this may be ok for your INSERT query, it will not allow the check_list field to be updated. So you will need to change the code for updates from this:
if(!empty($_POST['check_list'])) {
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
to this:
$checkboxes = empty($_POST['check_list']) ? '' : implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
You may also want to change the insert code in the same way if you want to insert a record even when the user doesn't check any checkboxes.
Thanks to #Phil for his input.
I think I see a couple of problems. I see this line:
$job_number = $_POST["job_number"];
But then I see you use this:
if($job_number["result"] == "true"){
So I ask, is $job_number an array or just a string/value?
Also, unchecked checkboxes don't submit a value. And since you test for a not empty $_POST['check_list'] value your UPDATE will never run. Remove the ! character.

PHP put data from database into form

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

Simple PHP task of updating database with radio buttons

Front-end designer here, not a PHP developer and I really need the help. Need to make a system that will allow the client to log into their own area to update a table. The table will have about 20 records and each row will be edited with radio buttons (4 choices). Only 2 columns, one for ID and one called status (the editable data).
The viewer will only see the changes made by the client and a background color change to that row depending on the status, which means the editable part will have to hold 2 pieces of data (integer value to change color and the name of the status, e.g. value of the radio button to change color, and label of button to echo the text into the cell). Will deal about login system later...
Database set-up:
Database: test
Table: fire_alert
Structure:
id (INT, PRIMARY); color(INT); warning(VACHAR);
connect.php:
<?php
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'test';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die("Could not connect to server ... \n" . mysql_error());
mysql_select_db($db)
or die("Could not connect to database ... \n" . mysql_error());
?>
view.php:
<div id="container">
<?php
// connect to the database
include('connect.php');
include("header.php");
// get results from database
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
// display data in table
echo "<table>";
echo "<tr> <th>Area</th> <th>Status</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($result)) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['warning'] . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
echo '<td>Change Area Status</td>';
?>
</div>
<body>
</body>
</html>
edit.php (client access only) no dynamic data changes yet, hardcoded HTML so far:
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="container" class="edit">
<div id="radio1">
<?
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
?>
<table class="edit">
<tr><th>Area</th><th>Status</th></tr>
<tr>
<td>1</td>
<td>
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" /><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" /><label for="radio4">Closed</label>
</form>
</td>
</tr>
</table>
</div>
<?php echo '<td>Update</td>'; ?>
</div>
The simplest way to run this update (or the way I use anyways) is by leveraging javascript. Have each section of radio blocks in its own form that submits automatically onChange, and include a hidden variable to indicate page submission. Then just write a function to update the database, based on the inputted user's id (or however you're validating) and their selection choice...
Something like:
if($_POST["submit"] == 1)
{
$id = $_POST["id"];
$radio = $_POST["radio"];
$query = "UPDATE fire_alert SET warning = '$radio' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
}
You have a problem with how you formatted your view.php link, that line should be as follows:
'Update'; ?>'
Though the above won't quite work as you're intending since it's not submitting the form, so the radio button values won't be passed... instead you should do:
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" onChange="this.submit()"/><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" onChange="this.submit()"/><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" onChange="this.submit()" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" onChange="this.submit()"/><label for="radio4">Closed</label>
<input type="hidden" name="id" value="<?=$row["id"]?>" />
</form>
And you'll need to edit your php to reflect that difference as well

Categories