PHP put data from database into form - php

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

Related

html/php forms with survey database

I hope someone can help me! I try to make a form with input from mysql. I want a statement to come from a database. Following this I want a user to be able to give a value 1-7(strongly disagree - strongly agree). I want the number of questions be based on my MySQL query. The main reason for this is that I can reuse the code for different types of surveys.
The problem is: I can't get the questions into a single form with separated values, linked to the question. I'm guessing it has something to do with the name= part. I think the name should be related to the database query somehow but I can't find out what the solution is.
If someone could help me I would be very thankful. Also if someone knows a good book or online course/video explaining how to make a online survey tool it would be very helpful.
This is what I have so far:
<?php
echo '<form action="results.php" method="post">';
global $connection;
$sql = "SELECT * FROM questions";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["question"];
echo "<br>";
echo ' <input type="radio" name="likkert" value=1>
<input type="radio" name="likkert" value=2>
<input type="radio" name="likkert" value=3>
<input type="radio" name="likkert" value=4>
<input type="radio" name="likkert" value=5>
<input type="radio" name="likkert" value=6>
<input type="radio" name="likkert" value=7>
<br>';
}
} else {
echo "0 results";
}
echo '<input type="submit"></form>';
?>
Assuming the fact that you have an id column, associated with each question, in questions table, you have to include this id column value (which should be unique) with each question's rating options, like this:
// your code
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["question"];
echo "<br />";
?>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=1>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=2>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=3>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=4>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=5>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=6>
<input type="radio" name="likkert[<?php echo $row["id"]; ?>]" value=7>
<br />
<?php
}
} else {
echo "0 results";
}
// your code
And after form submission, process the questions and their corresponding ratings like this:
foreach($_POST['likkert'] as $questionId => $rating){
// your code
}

Setting a radio button into session to retain checked state

I am trying to store the input value of a radio button and storing that intoa session so that if the user roams around the site the radio remains checked unless they switch it themselves and then the new selection remains checked.
<form action="" method="POST" id="reportSwitch">
<input checked type="radio" name="reportType" id="leadership" value="1" <?php if($reportType == 1){
echo 'checked';} ?>>
<label for="leadership">Leadership</label>
<input type="radio" name="reportType" id="fundementals" value="2" <?php if($reportType == 2){
echo 'checked';} ?>>
<label for="fundementals">Fundementals</label>
</form>
<?php
$_SESSION['reportType'] = $_POST['reportType'];
$reportType = $_SESSION['reportType'];
if(isset($reportType)){
} else{
$reportType = 1;
}
?>
I cannot seem to to get it to remain in a checked state...
Put the value in session and use the session variable to populate value in radio button in place of using extra variable.
By populating from session It will help to retain in all pages.
<?php
$_SESSION['reportType'] = $_POST['reportType'];
?>
<form action="" method="POST" id="reportSwitch">
<input type="radio" name="reportType" id="leadership" value="1" <?php if($_SESSION['reportType'] == 1){
echo 'checked';} ?>>
<label for="leadership">Leadership</label>
<input type="radio" name="reportType" id="fundementals" value="2" <?php if($_SESSION['reportType'] == 2){
echo 'checked';} ?>>
<label for="fundementals">Fundementals</label>
</form>
check this code
<?php
session_start();
$_POST['reportType'] = 1; // for testing it is set define value , you can change
if(isset($_POST['reportType'])){
$_SESSION['reportType'] = $_POST['reportType'];
$reportType = $_SESSION['reportType'];
} else {
$reportType = $_SESSION['reportType'];
}
if(!isset($reportType)){
$reportType = 1;
}
?>
<form action="" method="POST" id="reportSwitch">
<input checked type="radio" name="reportType" id="leadership" value="1" <?php if($reportType == 1){
echo 'checked';} ?>>
<label for="leadership">Leadership</label>
<input type="radio" name="reportType" id="fundementals" value="2" <?php if($reportType == 2){
echo 'checked';} ?>>
<label for="fundementals">Fundementals</label>
</form>

Dynamic radio button with self-post using PHP & MySQL

I'm drawing data from a MySQL database that dynamically places a question with 4-5 radio button choices for the answer. These radio buttons all belong to the same group, $quest_name. The first pass of the while statement will create 4 radio buttons belonging to radio group "question_1".
It creates 30-40 of these questions on a page, each with 4 radio buttons. I want the user to fill in all there answers and the page to post back to itself with the users answers still selected and then display if they were correct or not (functionality I still have to add).
I'm trying to follow http://www.w3schools.com/php/php_form_complete.asp as an example, but use a dynamically created radio button name instead.
This is what I have thus far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$quest_num = $row["id"];
$question = $row["question"];
$option_1 = $row["option_1"];
$option_2 = $row["option_2"];
$option_3 = $row["option_3"];
$option_4 = $row["option_4"];
$option_5 = $row["option_5"];
$answer = $row["answer"];
$quest_name = "question_" . $row["id"];
echo "(" . $quest_num . ") " . $question . "<br>";
?>
<label>
<input type="radio" name=<?php echo $quest_name ?>
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
value=<?php echo $option_1 ?>><?php echo $option_1 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_2 ?>><?php echo $option_2 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_3 ?>><?php echo $option_3 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_4 ?>><?php echo $option_4 ?>
</label>
<br>
<br>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit">
</form>
The part causing me grief so far is:
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
I have also tried:
<?php if (isset($quest_name) && $quest_name == $option_1) echo "checked"; ?>
and:
<?php echo (isset($quest_name) && $quest_name == $option_1) ? "checked" : ""; ?>
How do you post back to the same page what they've selected? Like in this case I'm trying to say if "question_1" is set and "question_1" is equal to "converter" (the first radio button option) then have it checked when submit button is clicked.
I'm not that good at web development, but I'm trying to create a website to help my fellow electrical technician classmates.
Thanks for any help.
EDIT :
Using this line of code fixed the issue:
<?php if(isset($_POST[$quest_name]) && $_POST[$quest_name]==$option_1) { echo 'checked="checked"'; } ?>
What you need is called Radio Group. In HTML layer it is created with same name for all and different values for each like this:
<p>
<label>
<input type="radio" name="RadioGroup1" value="Value1" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Value2" id="RadioGroup1_1">
Radio</label>
<br>
</p>
And when you want to get the user input in php layer you go like this:
<?php
//check if Radio Group 1 is set
if(isset($_POST['RadioGroup1'])) {
// print the value of Radio Group 1 choice
echo $_POST['RadioGroup1'];
}
?>
When you want to create a Selected Radio in HTML layer you go like this:
<input name="RadioGroup1" type="radio" id="RadioGroup1_1" value="radio" checked="checked">
So you have to check if user inputs the value of which radio like this:
<label>
<input type="radio" name="RadioGroup1" value="value1" id="RadioGroup1_0" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value1') { echo ' checked="checked"'; } ?>>
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="value2" id="RadioGroup1_1" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value2') { echo ' checked="checked"'; } ?> >
Radio</label>
You could use the following:
<input type="radio" name="<?php echo $quest_name ?>" value="<?php echo $option_1 ?>"
<?php if (isset($quest_name) && ($quest_name == $option_1)) echo "checked"; ?> />

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>

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