saving answers in an online test and sending them to database - mysql

I'm asked to write an online test. I have 2 tables, one includes questions (2 fields, one for id and one for question text). And another table for saving answers (with 3 fields, one for id, one for question id and one for the answer).
Here's how I've written it so far:
<form name="test" method="post" action="index.html">
<div class="slideshowContainer">
$question_query=dbquery("SELECT * FROM questions");
while($question_array=dbarray($question_query)){
echo'
<div class="question">
'.$question_array['question_text'].'
<br />
<textarea name="'.$question_array['id'].'"></textarea>
</div>
';
}
echo'
<input id="finish" type="submit" name="finish_test" value="send" />
</div>
</form>';
I'm also using cycle plugin so users can see the questions as slides and write the answers in each textarea provided for each specific question.
What I can't do is the way I should write the if(isset($_POST['finish_test'])) part. Because as I know in this way, the received data is in the form of an array. So I thought I might need another for or while element when I'm gonna save the answers and send them to my database.
What can you suggest?

Sure you are gonna need to loop through the results of the $_POST but its nice to make different id for each of the text areas in your code. That way you can identify which are which answers. So to do that I would do something like this.
while($question_array=dbarray($question_query)){
i = 0;
echo'
<div class="question".i>
'.$question_array['question_text'].'
<br />
<input id='question' type='hidden' value="'.$question_array['id'].'"/>
<textarea name="answer".i></textarea>
</div>';
i++;
}
Now since I know that i starts with 0 and ends when the questions end I can loop through that and access $_POST['answer'.i] and make the insertion.
while ($_POST['answer'.$i]) {
$i = 0;
//insert query after establishing connection, which i believe you got figured out
$sql = 'INSERT INTO ANSWERS VALUES ($_POST['answer'.$i], $_POST['question'.$i])';//Note you must have the question id in some hidden input field
$result = mysql_query( $sql, $conn );//where $conn is your connection object
//after this you might want to do something with the $result,
$i++;
}

Related

HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.
I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.
I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?
Here is my current code:
<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button>
<hr>
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);
if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];
?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
}
}
?>
</div>
</form>
if(isset($_POST['remove_dates'])){
$date_id = $_POST['date_id'];
}
I believe if you add this: [], to the name attribute, like this: <input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">. Then it will be handled as an array, which you can loop through with a foreach loop. and insert it into a database (or whatever you like).
Declare the name as an array, like as follows:
<input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">.
On submitting it will be handled as an array,
Then, you can loop the values of an array and for each element of an array use the id to remove the dates.

How do I search a table for multiple rows?

So this is my first question on stackoverflow and I've searched for day's but can't find the results I am looking for. I'm not looking for someone to write the code for me as I prefer to figure it out on my own, but I am looking for some assistance on finding how to do it.
My problem is I don't know how to word my search for what I'm looking for and this is what I want to do. I want to be able to search a MySQL database by using keywords such as "U10 Mustangs" where U10 would be data in a row called 'divisions' and Mustangs would be data in a row called 'club', I know I can use the OR statement like this
(`division` LIKE '%".$query."%') OR (`club` LIKE '%".$query."%')
but that only allows me to search by division or club not both. So basically I'm looking for a tutorial to show me how I can search by more than one keyword. I'm sure I'm wording this wrong and that's why I'm unable to find what I want.
I'm new to MySQL and PHP so please be understanding if this makes no sense!
*UPDATE*
here is my search code:
<body>
<?php include 'menu.php';?>
<br/><br/><br/>
<div id="searchcontainer" style="width: 55%; height: 132px;">
<fieldset style="width: 330px"><legend>Search Criteria</legend>
<form action="search.php" method="POST">
<td>Enter Search</td><td> <input type="text" name="query"/></td><td> <input type="submit" name="submit" id="table_button" value="Search" action="search.php"/></td>
<br />
</form>
</fieldset><br/>
<fieldset><legend>Search Results</legend>
<?php
include 'connect/local_connect.php';
$query = $_POST['query'];
// gets value sent over search form
// $min_length = 3;
// you can set minimum length of the query if you want
// if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM players
WHERE (`team_name` LIKE '%".$query."%' AND `division` LIKE '%".$query."%') OR (`last_name` LIKE '%".$query."%') OR (`division` LIKE '%".$query."%') ORDER by id ASC") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `first_name`, `any`
// players is the name of our table
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
}
else{ // if there is no matching rows do following
echo "<font color=red>No Results!</font>";
?><br/><br/>
<?php
}
// else{ // if query length is less than minimum
// echo "Minimum length is ".$min_length;
// }
// Define $color=1
$color="1";
echo '<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0">';
echo '<th>ID</th><th>Club</th><th>Last Name</th><th>First Name</th><th>Division</th>';
while($rows = mysql_fetch_array($raw_results)){
echo "<tr bgcolor='#fff000'>
<td><center>".$rows['id']."</td></center><td><center>".$rows['club']."</center></td><td><center>".$rows['last_name']."</td></center><td><center>".$rows['first_name']."</center></td></td><td><center>".$rows['division']."</center></td></td></tr>";
}
echo '</table>';
mysql_close();
?>
</fieldset>
</div>
</body>
Are yu looking for concat
where CONCAT(`division`,' ',`club`) like '%".$query."%'
I will suggest to create a full text index on division and club like this FULLTEXT (club,division)
and search using query like this
SELECT * FROM db
WHERE MATCH (club,division)
AGAINST ('search');
'...but that only allows me to search by division or club not both...'
You can split your search string in words and then use a condition like this
SELECT *
FROM table1
WHERE (division LIKE '%U10%' AND club LIKE '%Mustang%')
OR (division LIKE '%Mustang%' AND club LIKE '%U10%')
Here is SQLFiddle demo

Submit form to calculate quadratic equation

Am just learning html. I need to write code that solves the quadratic equation formula. I tried php code embeding in html but am getting blank output. How do I get user values a, b, c and display conditional answers?
Here's a simple example of what you need to do. First make a HTML form:
<form method="post" action="index.php">
<input type="text" name="a" value="Enter 'a'" />
<input type="text" name="b" value="Enter 'b'" />
<input type="text" name="c" value="Enter 'c'" />
<input type="submit" name='calc' value="Calculate" />
</form>
There is your form. Now the calculations:
<?php
// Check if the form is submitted
if (isset($_POST['calc'])) {
//assign variables
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
//after assigning variables you can calculate your equation
$d = $b * $b - (4 * $a * $c);
$x1 = (-$b + sqrt($d)) / (2 * $a);
$x2 = (-$b - sqrt($d)) / (2 * $a);
echo "x<sub>1</sub> = {$x1} and x<sub>2</sub> = {$x2}";
} else {
// here you can put your HTML form
}
?>
You need to do more checks on it, but as I said before this is a simple example.
Edit: learn from the source , the official php site: http://php.net/manual/en/tutorial.forms.php
1.Create a form with the fields you want. <form method='post' ....>...</form>
2.The user submit the form and then write a PHP code which get the posted data ($_POST)
and manipulate it according to the quadratic equation formula.
3.Echo the result.
I have smaller example.
This file sends data from form to itself. When it sends something - result of condition
$_SERVER['REQUEST_METHOD']=='POST'
is true. If its true - server process code in "if" block. It assigns data sent from form to 2 variables, then adds them and store in "$sum" variable. Result is displayed.
<html>
<body>
<form method="POST">
<p>
A: <br />
<input name="number_a" type="text"></input>
</p>
<p>B: <br />
<input name="number_b" type="text"></input>
</p>
<p>
<input type="submit"/>
</p>
</form>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') // process "if block", if form was sumbmitted
{
$a = $_POST['number_a'] ; // get first number form data sent by form to that file itself
$b = $_POST['number_b'] ; // get second number form data sent by form to that file itself
$sum = $a + $b; // calculate something
echo "A+B=" . $sum; // print this to html source, use "." (dot) for append text to another text/variable
}
?>
</body>
</html>
You need PHP server to test/use this! PHP file must be processed by web server, which creates page. Opening php file from disk will not work. If you need more explanations - ask for it in comments.

fill a select html with mysql table rows

I'm writting a web app, I'm doing a html form with javascript to validate the data, I'm using a servlet to insert the data in a DB, but I need, when the form load, fill a select in the html form with the rows of a table in a MySql DB, I think I have to make a query in a ResultSet and then fill the select in the html form with this info, and then use the HttpServletResponse, but I have no idea how to make this
Use PHP to access the database and then put it into the form. Something like this:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM table_name WHERE id='$id'");
$info = mysql_fetch_array($result))
$name = $info['name'];
$email = $info['email'];
$anotherField = $info['another_field'];
In this, the info array has all of the database data in it of the id. But of course you would change the values and stuff. Change table_name to the table name, and if you are going to do something in the URL like ?id=373384 or something, then this will work. (I would assume you are doing it this way.) But, if it isn't 'id', just change WHERE id='$id' to what is in the database to identify a line.
$info['name']; would be the "name" column in your table. But, you can change 'name' and stuff to what you have in your database.
Here is the form code to pre-fill it with data:
<form>
<input type="text" name="name" value="<?php echo $name ?>" />
<input type="text" name="name" value="<?php echo $email ?>" />
<!--etc...-->
<input type="submit" value="Submit" />
</form>
You would need to change a lot of this, but I'm sure you get the point of it. :)
Note: This is not a simple copy+paste script. You will have to do a lot of charing because I don't know what your table values are and stuff.
If you have any questions, please do ask.

textarea post into mysql not working

I have a textarea in a form that im trying to POST into a mysql database. However, when i insert the values, i get about 5 lines in the database. 4 of them have no information or minimal information and one of the lines is how i want it. How can i get rid of the other four lines? thanks.
EDIT: actually none of the lines have all the right info in the right spots and i have double checked the inset statement to make sure everything lines up.
the code:
<form method='POST' action="index.php">
<textarea id ='answerbox' autocomplete='off' cols="80" rows="5" name='answer'></textarea>
<input type='submit' value='submit'>
<?php
include 'connect.php';
$date=date("Y-m-d");
$time=time();
$answer=['answer'];
$user=$_SESSION['username'];
$id=$_GET['id'];
$put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
?>
Try:
<?php
if($_POST['answer'] != '')
{
include 'connect.php';
$date=date("Y-m-d");
$time=time();
$answer= $_POST['answer'];
$user=$_SESSION['username'];
$id=$_GET['id'];
$put=mysql_query("INSERT INTO solutions VALUES ('','0','$date','$time','$user', '$answer')");
}
?>
Your textarea is named as "answer" while its ID is "answerbox". You should be able to retrieve its value through $_POST['answer'];