exam form issues - php

i am really new on php. I try to make and examination project with php but i have some issues. I have exam form and this form have different type of inputs. For example some questions have combobox, some questions have textarea. I wrote my form code and i wanna learn how can i get all values from the form to the database.
my codes :
$question_id = $question_list['question_id'];
$answer_query = mysql_query("SELECT * FROM answers where question_id = $question_id ORDER BY answer_id ASC");
$total_answers = mysql_num_rows($answer_query);
if ($total_answers > 1)
{
<select name="answers[]" id="answers"> <option value="x">please select one</option>
while ($answer_list = mysql_fetch_array($answer_query)) {
<option value="<?PHP echo $answer_list['answer_id']; ?>"><?PHP echo $answer_list_list['answer_value']; ?></option>
else
{
while ($answer_list = mysql_fetch_array($answer_query)) {
<textarea name="answers[]" id="answers" rows="5" cols="100"></textarea>
so this is my answer listing part of my exam form. So as you see combobox values getting from database but textarea values will be filled by the users. So how can i get all values (answers from database in combobox (selected value) and textarea values which will be filled by users).

to get the form values to the database:
The HTML form has to be something like:
<form action="insert_into_db.php" method="POST">
<input type="text" id="answer1" name="answer1"/>
<textarea id="answer2" name="answer2"></textarea>
<input type="submit" value="POST ANSWERS" />
</form>
Then in the insert_into_db.php:
$answer1=$_POST['answer1'];
$answer2=$_POST['answer2'];

Related

Problem passing selected options - POST method

I'm having problems with the passing of the selected options by the client (the select box is a multiple choice select box built with jquery). Basically, through the POST method, it's passing just the last option selected by the client, ignoring all the others.
<form action="inserimento_fraseP.php" method="post">
sigla Frase P <input type="text" name="siglaP" required/> <br />
significato: <input type="text" name="significatoSiglaP" required/> <br />
<br />
sigla Frase H: <select class="mul-select" multiple="true" name="siglaH"> <?php select('siglaH', 'FraseH'); ?> </select>
<input type="submit" value="inserisci"/>
</form>
<?php
function select($name, $tabella){
include 'connessione_db.php';
$sql = "SELECT DISTINCT $name FROM $tabella ORDER BY $name";
echo $sql;
$result = $conn->query($sql);
echo "<option></option>";
while($row = $result->fetch_assoc())
{
echo "<option name='$row[$name]' value = '$row[$name]' > $row[$name] </option>";
}
}
?>
PLEASE change the name=siglaH[]
<select class="mul-select" name="siglaH[]" multiple="multiple">
---
</select>
you can check the by
print_r(implode(',', $_POST['siglaH']));
And ya one more thing I would like to tell you in your database store this field as varchar
Please set select name = siglaH[] then only you will get multiple data
I edited the name of the select from "siglaH" to "siglaH[]" and in the .php file the action refers to I was able to handle the selected options as an array.

Update Multiple Records without Checkbox

I need to update multiple records into a database on submit of a form. The form fields are repeating showing all the values but, the code doesn't seem to do anything. When someone hits submit, for each dataID presented in the hidden field, the progress and last_modified_date fields should be updated. I have googled and can't seem to find an answer anywhere. Any help would be appreciated. Thanks
Here is the update code:
if(isset($_POST['dataID'])){
foreach($_POST['dataID'] as $updateid){
$progress = $_POST['progress_'.$updateid];
$last_modified_date = $_POST['last_modified_date_'.$updateid];
$updateUser = "UPDATE data SET
progress='".$progress."',last_modified_date='".$last_modified_date."'
WHERE dataID=".$updateid;
mysqli_query($sdpc_i,$updateUser);
}
}
}
?><form method="post" name="form1" enctype="multipart/form-data">
<select title="progress" name="progress[]" id="progress" class="form-control form-control-sm-3">
<option selected value="">Select One</option>
<option value="Contract Sent">Contract Sent</option>
<option value="Approved">Approved</option>
<option value="With Legal">With Legal</option>
<option value="Declined">Declined</option>
<option value="Vendor Unresponsive">Vendor Unresponsive</option>
<option value="Approved/No Data Collected">Approved/No Data Collected</option>
</select>
<?php
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" id="dataID" value="<?php echo($district_results_private->getColumnVal("dataID")); ?>" />
<?php
$district_results_private->moveNext();
}
$district_results_private->moveFirst(); //return RS to first record
?>
<input name="last_modified_date[]" type="hidden" id="last_modified_date" value="<?php echo date('Y-m-d'); ?>" />
<input type="image" src="images/save.png" name="submit" id="submit" alt="Save" />
</form>
--------------------------------------------
UPDATE:
Thank you so much for your help! I did what you said and I am still getting these errors.
Notice: Undefined index: progress in /var/www/html/progress_workflow_multiple3.php on line 97
Notice: Undefined index: dataID in /var/www/html/progress_workflow_multiple3.php on line 98
Warning: Invalid argument supplied for foreach() in /var/www/html/progress_workflow_multiple3.php on line 98
Here is the code I have:
<?php
$stmt = mysqli_stmt_init($sdpc_i);
mysqli_stmt_prepare($stmt, "UPDATE data SET progress = ?, last_modified_date = CURDATE() WHERE dataID = ?");
mysqli_stmt_bind_param($stmt, 'si', $progress, $dataID);
$progress = $_POST['progress'];
foreach ($_POST['dataID'] as $dataID) {
mysqli_stmt_execute($stmt);
}
?>
Here is the form code:
<label for="progress"></label>
<span class="small_links">
<select title="progress" name="progress" id="progress" class="form-control form-control-sm-3">
<option value="">Select One</option>
<option>Contract Sent</option>
<option>Approved</option>
<option>With Legal</option>
<option>Declined</option>
<option>Vendor Unresponsive</option>
<option>Approved/No Data Collected</option>
</select>
</span>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<?php
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" value="<?php echo $district_results_private->getColumnVal("dataID"); ?>" />
<?php
$district_results_private->moveNext();
}
$district_results_private->moveFirst(); //return RS to first record
?>
</p>
</div>
</div>
<p> </p>
<p>
<input type="image" src="images/save.png" name="submit" id="submit" alt="Save" />
</form>
Your form has 3 essential parts (excluding the submit of course) for the user to interact with:
<select id="progress"> ...(progress field)
<input id="dataID"> ...(dataId fields) this may occur multiple times
<input id="last_modified_date"> ...(lastMod field)
The progress field will only occur once, so there is no benefit in structuring its data as an array. Furthermore, a select field will default to its first option, so there is no need for selected on the first option. Also, when the value value of an option is exactly the same as the option's text, you can safely omit the value attribute.
<select title="progress" name="progress" class="form-control form-control-sm-3">
<option value="">Select One</option>
<option>Contract Sent</option>
<option>Approved</option>
<option>With Legal</option>
<option>Declined</option>
<option>Vendor Unresponsive</option>
<option>Approved/No Data Collected</option>
</select>
The dataId fields are rightly given an array-type name. However, it is inappropriate to assign multiple elements with the same id attribute. If you application is not using the id attributes (for any fields), just omit the declaration(s). If you need to assign unique id attributes, you will need to provide an incrementing counter and append that counter to the end of the id value.
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" value="<?php echo $district_results_private->getColumnVal("dataID"); ?>" />
<?php
$district_results_private->moveNext();
}
The lastMod field can be completely omitted from the document. You are always passing the current date with the submission and don't want the user fiddling with it -- good news, you can hardcode that directly into your sql and the user won't be able to touch it.
As for the UPDATE queries, best practice indicates that you should be implementing a prepared statement and binding dynamic values to it in a loop for security and stability.
(Untested -- I never use procedural syntax)
$stmt = mysqli_stmt_init($sdpc_i);
mysqli_stmt_prepare($stmt, "UPDATE data SET progress = ?, last_modified_date = CURDATE() WHERE dataID = ?");
mysqli_stmt_bind_param($stmt, 'si', $progress, $dataID);
$progress = $_POST['progress'];
foreach ($_POST['dataID'] as $dataID) {
mysqli_stmt_execute($stmt);
}
p.s. I hope that data isn't your real table name -- because it is bad/imprecise/non-descriptive. Name it something intuitive/logical/expressive.

get selected value of a drop down which is populated with results from an SQL query

So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:
<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
<input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
<select name="Name_dropdown" id="name_dropdown" style="width: 200px" >
<?php
$ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";
$ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());
while ($row= mysql_fetch_array($ClientName_Result)){
echo "<option> $row[FullName] </option>";
}
?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>
In your ClientDetails.php file the value will be available using,
$name = $_POST['Name_dropdown'];
If you need to change a setting in the form document before submitting you can use jQuery. Something like
$('#name_dropdown').change(function(){
var option = $(this.options[this.selectedIndex]).val();
});

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

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