Simple PHP task of updating database with radio buttons - php

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

Related

Submitting a multiple checkbox form to MySql with php

I have a form with multiple fields: Textinputs, Checkboxes, Radios.. and I want to submit it to a MySQL database. When I comment the checkboxes HTML, and the corresponding php code, everything is working fine, and everything is submitted and saved in the DB. If I try to submit the checkbox-form and I uncomment it, nothing get submitted, and clicking on the submit-button doesn't make any effect.
How can I submit the value of the checkbox-field to the MySQL-Database as a string, with the values separated with a semi-colon? For ex. if the checkbox fields are: Ab, Cd, De, Fg - and "Ab" and "De" are checked, the following string gets submitted: "Ab;Cd"
Here is a part of my HTML-form:
<div class="row">
<div class="col-sm-4">
<fieldset class="form-group">
<label for="plattform">Platform</label>
<form id="formId">
<input type="checkbox" name="check_list[]" value="Android">Android
<input type="checkbox" name="check_list[]" value="iPhone">iPhone
<input type="checkbox" name="check_list[]" value="iPad">iPad
<input type="checkbox" name="check_list[]" value="Windows Phone">Windows Phone
</form>
<!-- <input type="checkbox" name="check_list[]" value="Android">
<input type="checkbox" name="check_list[]" value="iPhone">
<input type="checkbox" name="check_list[]" value="iPad">
<input type="checkbox" name="check_list[]" value="Windows Phone"> -->
</fieldset>
</div>
<div class="col-sm-4">
<fieldset class="form-group">
<label for="featured">Featured</label>
<div>
<input type="radio" name="featured" required>True</input>
</div>
<div>
<input type="radio" name="featured" required checked>False</input>
</div>
</fieldset>
</div>
here is a sample of my php-file:
<?php /* Attempt MySQL server connection. Assuming you are running
MySQL server with default setting (user 'root' with no password) */
/* Database connection start */
$servername = "localhost";
$username = "serverName_Here";
$password = "password_Here";
$dbname = "dbName_Here";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$stName = mysqli_real_escape_string($conn, $_POST['sName']);
$lgName = mysqli_real_escape_string($conn, $_POST['lName']);
$desc = mysqli_real_escape_string($conn, $_POST['desc']);
$Platform = '';
if(!empty($_POST['check_list'])) {
$counter = 0;
foreach($_POST['check_list'] as $check) {
if ($counter < 1) {
$Platform = $check;
} else {
$Platform = $excludePlatform + ';' + $check;
}
counter++;
}
}
$Platform = mysqli_real_escape_string($conn, $_POST['check_list']);
$sql = "INSERT INTO tableName_Here (stName, lgName, details_description, Platform) VALUES ('$stName', '$lgName', '$desc', '$Platform')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
} // close connection
mysqli_close($conn); ?>
You need to have the checkboxes within the form tags.
The easiest way is to put the form opening and closing tabs above and below the rest of the field code. The submit buttons should be within the form as well.
On the backend checkbox values will come through as an array. You can then do something like this if you want to save them comma separated.
$values = implode(', ', $_POST['check_list']);
First of all,Why you haven't used POST as method in form tag also you haven't used submit button.In that way you can access value of checkboxes in php like
$value=$_POST['check_list[]'];
Try this whole example,
Table Structure
CREATE TABLE IF NOT EXISTS `games` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`game_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
<?php
include_once("yourconfig.php"); //include your db config file
extract($_POST);
$check_exist_qry="select * from games";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_game=explode(',',$my_value['game_name']);
}
if(isset($submit))
{
$all_game_value = implode(",",$_POST['games']);
if($total_found >0)
{
//update
$upd_qry="UPDATE games SET game_name='".$all_game_value."'";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO games(game_name) VALUES('".$all_game_value."')";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[]" value="1" <?php if(in_array(1,$my_stored_game)){echo "checked";}?>><label>Football</label><br>
<input type="checkbox" name="games[]" value="2" <?php if(in_array(2,$my_stored_game)){echo "checked";}?>><label>Basket Ball</label><br>
<input type="checkbox" name="games[]" value="3" <?php if(in_array(3,$my_stored_game)){echo "checked";}?>><label>Pool</label><br>
<input type="checkbox" name="games[]" value="4" <?php if(in_array(4,$my_stored_game)){echo "checked";}?>><label>Rugby</label><br>
<input type="checkbox" name="games[]" value="5" <?php if(in_array(5,$my_stored_game)){echo "checked";}?>><label>Tennis</label><br>
<input type="checkbox" name="games[]" value="6" <?php if(in_array(6,$my_stored_game)){echo "checked";}?>><label>Cricket</label><br>
<input type="checkbox" name="games[]" value="7" <?php if(in_array(7,$my_stored_game)){echo "checked";}?>><label>Table Tennis</label><br>
<input type="checkbox" name="games[]" value="8" <?php if(in_array(8,$my_stored_game)){echo "checked";}?>><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
this is just basic example and query i have added in this example, you can learn from this basic example and i think this is very useful for you... if useful than give correct answer for this solution

Call a Row By Clicking A Button MYSQL/PHP

I am creating an online exam. My layout is to show one question at a time and below it is the multiple choice. At the bottom of the multiple choice is a 'Next' button that when click will show the next question.
The questions and multiple choice are stored in a database.
The problem is, the next button functions, but it redirects me to another page. When all I want is to hide the previous question and show the next question when the next is clicked.
This is my code:
db
CREATE TABLE `english` (
`E_QueID` int(11) NOT NULL,
`Question` text NOT NULL,
`A` text NOT NULL,
`B` text NOT NULL,
`C` text NOT NULL,
`D` text NOT NULL,
`E` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
html
<div class="col-sm-8 bt-query">
<br>
<h4><left>Question 1</left> <right><div class="timer" data-seconds-left="20"></div></right></h4>
<br>
<?php
$query="SELECT * FROM english ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $query);
if (!$result) { // add this check.
die('Invalid query: ' . mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
echo $row['Question']. "<br />";
echo $row['A']. "<br />";
echo $row['B']. "<br />";
echo $row['C']. "<br />";
echo $row['D']. "<br />";
echo $row['E']. "<br />";
}
?>
<br>
<form action="englishq.php" method="get">
<input type="submit" name="next" value="Next">
</form>
</div>
englishq.php
<?php
$hostname = "localhost";
$user = 'root';
$password = '';
$db = 'questions';
//databse connection
$conn = mysqli_connect("$hostname", "$user", "$password", "$db")or die(mysqli_error());
if(isset($_GET['next'])){
$query="SELECT * FROM english ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $query);
if (!$result) { // add this check.
die('Invalid query: ' . mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
echo $row['Question']. "<br />";
echo $row['A']. "<br />";
echo $row['B']. "<br />";
echo $row['C']. "<br />";
echo $row['D']. "<br />";
echo $row['E']. "<br />";
}
}
?>
Leave the form's action parameter blank, so the form will submit back to the current page. Then use PHP to read the last question submitted and load the next one to display it to the user. You could use a hidden input field to keep track of which question was submitted.
Form code:
<form action="" method="post">
<input type="hidden" name="question_number" value="<?php echo $mynumber; ?>" />
<input type="radio" name="answer" value="A." /><?php echo $answerA; ?> <br/>
<input type="radio" name="answer" value="B." /><?php echo $answerB; ?> <br/>
<input type="radio" name="answer" value="C." /><?php echo $answerC; ?> <br/>
<input type="radio" name="answer" value="D." /><?php echo $answerD; ?> <br/>
<input type="submit" name="next" value="Next">
</form>
PHP code:
if (isset($_POST['question_number']))
{
// Record the last answer
$stmt = $db->prepare("INSERT INTO user_answer_table (answer_field) VALUES (':answer')");
$stmt->bindParams(':answer', $_POST['answer']);
$stmt->execute();
// Load the next question
$stmt = $db->prepare("SELECT * FROM question_table WHERE question_id = :questionid");
$stmt_>bindParams(':questionid',$_POST['question_number']+1);
$stmt->execute();
}
Check if a $_POST contains an answer. If yes, check if it is correct. Give a feedback. On incorrect answer you might ask the same question again, else generate a new random id.
Place a form around the page content, that sends the data back to the same script.
<form action="" type="post">
Give the client the question id.
<input type="hidden" name="qid" value="<?php echo $row['E_QueID';?>">
Inside the loop over the data table generate some radio buttons
<div>
<input type="radio" id="ansA" name="answer" value="A">
<label for="ansA"><?php echo $row['A'];?></label>
</div>
<div>
<input type="radio" id="ansB" name="answer" value="B">
<label for="ansB"><?php echo $row['B'];?></label>
</div>
Add a submit button and close the form tag.

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

Inserting SQL Database values in HTML update form

I'm trying to make a form that will allow a user to edit records in the database.
My main.php is a table where the user can click on a record to edit / delete:
echo "<td>".$row["fname"].", ".$row["first_name"]."</center></td>";
echo "<td><center>".$row["gender"]."</center></td>";
echo "<td><center>".$row["city"]."</center></td>";
echo "<td><center>".$row["extra"]."</center></td>";
echo '<td><center><img src="edit_icon.png"/><center></td>';
echo '<td><center><img src="delete.gif"/><center></td>';
echo "</tr>";
}
?>
<input type="hidden" name="p_ID" value="<?php echo $row["p_ID"]?>"></input>
<input type="hidden" name="lname" value="<?php echo $row["lname"]?>"></input>
etc..
When the user clicks the edit icon, it redirects to the form page where I need the values ($row['fname']) to show up in their respective fields. I've tried suggested solutions but I still don't know how to accomplish this correctly. I keep getting errors. This is what I've tried with my form.php
#$submit=$_POST['submit'];
#$lname=$_GET['lname'];
#$gender=$_GET['gender'];
#$city=$_GET['city'];
#$extra=$_GET['extra'];
?>
Last name <input type="text" name="lname" value= <?php echo $lname ?>><br><br>
Gender <input type="radio" name="gender" value="M" <?php if($gender=="M") {echo "checked";} else {echo " ";} ?>/>M
<input type="radio" name="gender" value="F" <?php if($gender=="F") {echo "checked";} else {echo " ";} ?>/>F<br><br>
City <select name="city">
<option value="x">Select</option>
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
$num_results=mysql_num_rows($result);
mysql_close($db);
for ($i=0;$i<$num_results;$i++)
{
$row=mysql_fetch_array($result);
echo"<option value='".$row['city_id']."'", $row['city_id']==$row['city_ID']? " selected='selected'" : '',">".$row['city']."</option>";
}
?>
</select><br><br>
Extra <input type="checkbox" name="extra" value="yes" <?php if($extra=="yes") {echo "checked";} else {echo " ";} ?>/><br><br>
And I'm not really concerned with any SQL injections or anything right now, I just need this working. I'd be grateful for any help!
Errors: Undefined index for everything
You are closing the connection before mysql_query is used in mysql_fetch_array.
You are trying to fetch the rows incorrectly.
mysql_close isn't needed unless you have a lot of processing after the query because the connection is closed after the script has finished running anyway.
Also, declare your variables like this to remove the undefined index errors:
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
Note: this also protects against sql injection but mysql_real_escape_string() will only work after you connect.
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
//other vars here
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['city_id']."'>".$row['city']."</option>";
}
mysql_close(); // now you can close the connection
?>
What you need is form submission check. Here is the general form of a single-page update script:
<?php
if(isset($_POST['submit'])) {
// Form was submitted, process it and display message
exit(); // Prevent form from being displayed again
}
?>
<!doctype html>
<html>
<body>
<form method="POST" action="form.php">
<!-- fields -->
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Set mysql values from radio buttons in html form

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

Categories