How to show results of a form upon submission - php

Using WordPress, so PHP, HTML, CSS, JavaScript what is the best method of populating the results of a form upon submission? I could have a form with ddl, radio buttons, etc.
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
What is the best way of populating the results i.e. "67% of users are Female" and "30% ride bikes" on the same page once the submit button is triggered?

Try something along these lines:
script.php
----------
<html>
<body>
<form method=post action=script.php>
your form here...
</form>
<? if($_SERVER["CONTENT_LENGTH"]>0) {
//form was submitted to script, so process form inputs here and display results...
}
?>
</body>
</html>

<form action="phpfile.php" method="Post">
...form here
</form>
phpfile.php:
<?php
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}//etc..
//To show the result, simply echo it:
echo $sex;
You'll need some sort of storage system to be able to calculate the amount of each.
So what you would need to do is write a simple query where the value of the field is male or female. Then you can easily calculate it.

What you will need to do is add the form results to the database, then find the total number of results for both categories, then calculate the percent female and the percent bike.
The form page:
<html>
<?php
if(isset($_GET['status']) && $_GET['status'] == "values") {
//connect to DB and select table
$male = count( mysql_query("SELECT gender FROM Table WHERE gender='male'"));
$female = count (mysql_query("SELECT gender FROM Table WHERE gender='female'"));
$car = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='car'"));
$bike = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='bike'"));
$totalResults = $male + $female;
$totalVehicles = $car + $bike;
$percentFemale = 100 * ($female / $totalResults);
$percentFemale = number_format($percentFemale, 0);
$percentBike = 100 * ($bike / $totalVehicals);
$percentBike = number_format($totalBike, 0);
echo "<p>" . $percentFemale . "% of users are female. </p>";
echo "<p>" . $percentBike . "% of users use bikes. </p>";
} else { ?>
<form action="formProcessor.php" method="POST"><!-- You could also use GET -->
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
<?php } ?>
</html>
The formProcessor.php Page:
<?php
if(isset($_POST["sex"]) && isset($_POST['vehicle'])) {
//Connect to MySQL DB and select table here
$sex = $_POST['sex'];
$vehicle = $_POST['vehicle'];
mysql_query("INSERT INTO Table(sex, vehicle) VALUES($sex, $vehicle)"); //You may also want to add an id column, but...
//Close mysql connection
header("Location: /form.php?status=values");
die();
} else {
die("There was an error in your submission.");
}
?>
I think this answers your question, you've got a way to find the percent of female users and users on bikes. If you need that to be dynamic and show only the greater amount (or show both or something) just add a comment. This also assumes you are not using PDO, if you are, I can adjust the code. I just wrote the code, so I don't know for sure if it works, but here you go!

Related

PHP (check or uncheck) a checkbox from Database

So I'm using a checkbox to insert data into MySql database.
When check it stores "finish"
When unchecked if stores "pending"
Now for an edit feature, I have to fetch and display the data from the database. I need the checkbox to be checked or unchecked if it is stored as finish or pending. Appreciate your help, thank you.
The code to fetch the data is shown below:
<?php
$query = ("SELECT * FROM ebook WHERE Eid='" . $Eid . "'");
$result = mysqli_query($con, $query);
$rows = mysqli_fetch_assoc($result);
?>
Displaying data and checkbox:
<html>
<input type="text" name="title" value="<?php echo $rows["Title"]; ?>">
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" />
</html>
Put a condition echo inside the input.
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" <?php if ($rows['status'] == 'finish') { echo "checked"; } ?>/>

set value on multiple row from column based on previous query php/mysql

running the following query ($box is yes or no from previous page):
$raw_results = mysqli_query($con,"
SELECT *
FROM `tbl_case`
WHERE `self_paid` ='$box'
AND `case_date_closed` BETWEEN '$startdate' AND '$enddate'
");
It displays all the fields correctly, and finishes with another checkbox
with the radio button below, if selected yes, it should set yes to paid_state on all previously returned $id'
<h1> Would you like to set these as paid to self ?
<form>
<form action="selfpaid.php" method="POST">
<input type="radio" name="state" value="yes" checked> Yes<br>
<input type="radio" name="state" value="no"> no<br>
<input type="submit" style="margin-left:80px; width:150px; height:30px;" value="Set state" />
</form>
<?php
if(isset($_POST['state']) && $_POST['state'] == "yes")
{
mysqli_query($con,"UPDATE tbl_case SET self_paid = 'yes' WHERE id = '$id'");
echo "Setting paid statesucessfull.";
}
else{
echo "paid_state not set";
}
?>
i am guessing it needs to be pulled from the db, and put all those $id in another array var, but i can;t figure out how, and then loop over that array .. can someone point me in the right direction ?

SQLite statement won't take multiple values

I've looked through a lot of questions, so forgive me if there is one that may help, but I've not been able to figure this out.
So I have a simple HTML form, that takes the users input for three categories: multiplayer, platform, and genre. This is the html code
<form method="post" action="gamebuddy.php">
<div class="players">
Please select one (or both) of the following: <br>
<input type="checkbox" name="players[]" value="No">Single Player<br>
<input type="checkbox" name="players[]" value="Yes">Multiplayers<br>
</div>
<div class="platform">
Please select your game system(s): <br>
<input type="checkbox" name="platform[]" value="XBOX">Xbox<br>
<input type="checkbox" name="platform[]" value="PS3">PS3<br>
<input type="checkbox" name="platform[]" value="PC">PC<br>
<input type="checkbox" name="platform[]" value="Wii">Wii<br>
</div>
<div class="genre">
Please select the genre(s) of game you would like: <br>
<input type="checkbox" name="genre[]" value="Action" >Action<br>
<input type="checkbox" name="genre[]" value="Casual">Casual<br>
<input type="checkbox" name="genre[]" value="Roleplaying">Role-Playing<br>
<input type="checkbox" name="genre[]" value="Shooter">Shooter<br>
<input type="checkbox" name="genre[]" value="Sports">Sports<br>
</div>
<div class="submit">
<input type="submit">
</div>
And then I have a PHP file that is used when the user clicks submit. Ideally, it takes the form inputs as a variable, and uses the SQLite statement to find the games the user can play based on his choices.
Here's the PHP code:
<div class="displaygames">
Based on your choices, these games seem suitable for you: <br>
<?php
if(!empty($_POST['players'])) {
foreach($_POST['players'] as $players) {
echo $players; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['platform'])) {
foreach($_POST['platform'] as $platform) {
echo $platform; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['genre'])) {
foreach($_POST['genre'] as $genre) {
echo $genre; //echoes the value set in the HTML form for each checked checkbox.
}
}
//This is to connect to the database
$db = new SQLite3('gamebuddy.db');
//Statement that uses variables to create list
$results = $db->query("SELECT * FROM games where multiplayer = '$players' and platform = '$platform' and genre is '$genre'");
//Displays List
while ($row = $results->fetchArray()) {
echo '<ul>';
echo $row['game'];
echo '</ul>';
}
?>
So everything works fine if you put in one answer for each category (for example, the user clicks "No" to multiplayer, "PS3" to platform, and "action" to genre). BUT if the user selects "Action" AND "Role-Playing", for some reason it only takes the last one the user selects, in this instance "role-playing".
So my question is how do I get the statement to show ALL of the games when there are multiple inputs.
Thank you for your help, I will answer any questions there may be, and of course mark the answer as solved if it helps. Thanks!
If u have array in for example $players, u can use implode function and "IN" statement in SQL:
"SELECT * FROM games WHERE multiplayer IN (".implode(",", $players).")"

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

PHP get input , radio , selection data and insert into MySQL table

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereā€”the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.

Categories