I'm facing such a problem,
I have a database bank with lots of questions and their joined answers 'multiple choice system'!
I wrote a PHP script to retrieve (15) questions each time a user enters the page, 'index.php' as a radio-buttons.
Now my bass asked me to change the method of showing the questions! so, instead of 15 questions at the same page! he asked to show one question per time, something like this:
================================================================================
1. Question TEXT:
a. 1st variant
b. 2nd variant
c. 3rd variant
d. 4th variant
<NEXT QUESTION>
================================================================================
so by clicking on the button which is a "submit" the script should redirect me to the second part of the file which must show the second question, and from the second as shown above to the third --> forth --> ... --> 15th question
================================================================================
1st question is: Correct //This part will check the correction/incorrection of the previous question -_-
2. Question2 TEXT:
a. 1st variant
b. 2nd variant
c. 3rd variant
d. 4th variant
<NEXT QUESTION>
================================================================================
bottom line, I am able to bring a 15 question on the page and after checking the answers I give the results. but I could figure out how to distribute these questions into individual pages!! as
'index.php?question=1'
'index.php?question=2'
'index.php?question=3'
...
'index.php?question=15'
Thank you guys!
so as I said, I wanted to distribute the results retrieved from one query into individual pages, and I came up with this idea,
1. Did the same query
SELECT * FROM database ORDER BY RAND() LIMIT 10
then I saved the IDz of the retrieved questions into an array just like that
$id = array();
$_SESSION[corr] = 0;
$_SESSION[incorr] = 0;
while ($row = mysql_fetch_assoc($query) {
$id[] = $row[ID];
}
Then I saved the array into a SESSION to pass it in every required page as follows
$_SESSION[ID] = $id;
after that I set a link such as
echo "<a href=test.php?question=1>Click To Start</a>";
and last but not least did something like this
if ($_REQUEST['question'] == '1') {
$id = $_SESSION['id'];
$sql = mysql_query("SELECT * FROM `test` WHERE `id` = '$id[0]'") or die("Error" .mysql_error());
$row = mysql_fetch_assoc($sql);
echo "<font color=green>Correct: " .$_SESSION[corr]. "</font></br>";
echo "<font color=red>Incorrect: " .$_SESSION[incorr]. "</font></br>";
echo "$row[v]<br>";
echo "<form action='test.php?question=2' method='POST'>";
echo "<input type=radio name=answer1 value=1>$row[o1]</input><br>";
echo "<input type=radio name=answer1 value=2>$row[o2]</input><br>";
echo "<input type=radio name=answer1 value=3>$row[o3]</input><br>";
echo "<input type=radio name=answer1 value=4>$row[o4]</input><br>";
echo "<input type=submit name=submit value=Check>";
echo "</form>";
$_SESSION['previous_id'] = $row['id'];
exit;
and in the next part "test.php?question=2"
I firstly checked if the previous question was answered correctly as the following
if ($_REQUEST['question'] == '2') {
$id = $_SESSION['id'];
$answer = $_POST['answer1'];
$grade = mysql_query("SELECT * FROM `test` WHERE `id` = {$_SESSION['previous_id']}") or die();
$right = mysql_fetch_assoc($grade);
if ($answer == $right[g]) {
$_SESSION['corr']++;
echo "<font color=green>Correct</font></br>";
}
else {
$_SESSION['incorr']++;
echo "<font color=red>Incorrect, check lesson #".$right[lvl]."</font></br>";
}
$sql = mysql_query("SELECT * FROM `test` WHERE `id` = '$id[1]'") or die("Error" .mysql_error());
$row = mysql_fetch_assoc($sql);
echo "$row[v]<br>";
echo "<form action='test.php?question=3' method='POST'>";
echo "<input type=radio name=answer2 value=1>$row[o1]</input><br>";
echo "<input type=radio name=answer2 value=2>$row[o2]</input><br>";
echo "<input type=radio name=answer2 value=3>$row[o3]</input><br>";
echo "<input type=radio name=answer2 value=4>$row[o4]</input><br>";
echo "<input type=submit name=submit value=Check>";
echo "</form>";
$_SESSION['previous_id'] = $row['id'];
exit;
}
That worked just 100% as I wanted, but it is just not feeling professional, because I had to rewrite that code, or copy and edit the same above shown codes lots of times, considering I am trying to post 10 or 15 questions separately..
hopefully that helps some one else!
Related
I'm trying to create a very easy stock managing system. I'm able to show all the items in my table 'parts' and i'm showing the amount in a textbox. However, when i change the value from, for example, 0 to 5 in the textbox and i press my submit button, it doesn't update the stock.
Below is my code, i don't have alot of experience with update querys but i've read about it on php.net, obviously.
<?php
echo "<table width=\"800\" class=\"nieuws\">";
$db=mysqli_connect("localhost","root","","lichtwinkel");
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<form method='post' action=''>";
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal' value=$row[voorraad] /></td>";
echo "<td><input type='submit' id='update' name='update' value='Update' /></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['aantal']) && $_POST['update']) {
$y = $_POST['aantal'];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '$y' WHERE partnr = $row[0]");
}
echo "</form>"
?>
Simply said, what i'm trying to achieve is the following:
Whenever i change the value displayed in the texbox, and i press my submit button, i want it to update the value in the database.
Does anyone know what i'm doing wrong? Any ideas? Articles i should read?
All help would be appreciated.
Thank you.
As i see, you were doing it wrong at all.
First you can't use form tag within more then one td element.
You were didn't close the form tag, only at end. (So if it loops 6 times, you will have 6 forms open, but one ended!).
At update, you're selecting row[0] - it's outside of loop with rows?
Even if you update it, it will show wrong results again. Update should be above selects! So it picks up newly updated value.
What to do:
First make one form for all updates.
Use your submit button to have value DATABASE_ID.
Make the name of "aantal" to "aantalDATABASE_ID".
At submit check for $_POST['update'], and use it's value (DATABASE_ID) to get input $_POST["aantal".$_POST['update']].
Do update, you have all you need.
Example:
<?php
echo "<form method='post' action=''>";
echo "<table width=\"800\" class=\"nieuws\">"
$db=mysqli_connect("localhost","root","","lichtwinkel");
if(isset($_POST['update']) && !empty($_POST['update'])) {
$y = $_POST['aantal'.$_POST['update']];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '".$y."' WHERE partnr = '".$_POST['update']."'");
}
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal".$row[0]."' value='".$row[voorraad]."' /></td>";
echo "<td><input type='submit' id='update' name='update' value='".$row[0]."' /></td>";
echo "</tr>";
}
echo "</table>";
echo '</form>';
?>
After all, take care about SQL Injections. "aantal" value is user input. As the submit value can be changed.
Hi I'm looking to insert a varible into a submit buttons name when I echo it via a loop so that each button has a unique name
$x=0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);
echo ("<table>");
echo ("<tr>");
echo ("<th>Name</th>");
echo ("<th>Level</th>");
echo ("<th>Stats</th>");
echo ("<th>Win Chance</th>");
echo ("<th>Action</th>");
echo ("</tr>");
while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo("<tr>");
echo("<th>".$row['username']." </th>");
echo("<th>Level: ".$row['Level']." </th>");
echo("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo("<th>Win Chance: ");
echo(CalculateWinChance($link,$row['Defence']));
echo("<input type='hidden' name='".$x."hidden1' value='".$row['Defence']."' />");
echo("<input type='hidden' name='".$x."hidden2' value='".$row['username']."' />");
echo("<th><input type='submit' name = 'Attack_Btn".$x."' onclick = 'BattlePlayers()' value ='Attack'></th>");
echo("</tr>");
$x=$x+1;
}
}
echo ("</table>");
I tried the above code but it does not change the name attribute? What am I doing wrong here?
you can put that as an answer can ill accept it :) – GregHBushnell
Posting from comments:
"$ is not empty its prining as expected 01234" - The leading zero is treated as an octal, that's why it's failing. . – Fred -ii
thank you very much that solved it :) what is an octal ? – GregHBushnell
References:
http://php.net/manual/en/language.types.integer.php
https://en.wikipedia.org/wiki/Octal
Footnote:
echo is a language construct and not a "function" per se. So, you can safely omit all of the (), since that's just more code than needed really.
Reference:
http://php.net/manual/en/function.echo.php
I'm making a quiz for my students. I would like to make it in such a way that you can only see question 2 after you solved question 1 (and so on).
My current idea is to make a web page for every question with a form on it:
<FORM action="test.php" method="post">
<I>12 is the right answer:</I>
<INPUT TYPE="text" NAME="name" SIZE="20" MAXLENGTH="30"><BR>
<INPUT TYPE="submit" VALUE="send">
</FORM>
And afterwards, I try to redirect from test.php to next.php whenever the answer is 12 and to current.php when the answer is not 12. Though, I am not able to make this work. Can anyone help me?
Have not written php code for a while now but will try to guide you.
No, you should not create a web page for each question. That is not a scalable approach. Imagine if you have to store 1000 questions over time,period.
Instead use dynamic page loading concept in php. Here what you should be doing:
1.Create a table in whichever database you are using with fields like
Id,question,option1,option2,option3,option4,correctAnswer
Create a php page like quiz.php which reads the question based on questionId stored in the session variable.
Lets say you show the first question in front page, displad the options and showed a submit button.
When the user clicks submit button what should happen is that the same quiz.php page will get called courtsy <form action="quiz.php"> with the user selected answer.
You can then check for the correct answer in php file since you have the correct answer stored in a variable which stores the database fetched result of first question, and if that is correct answer you can update the session with id of next question (increment by 1 or any other mechanism) and query the database table for that question id .
Your html should be written in such a way away which reads the current value stored in $row variable, which stores the result of the query w.r.t to questionId stored in session.
little bit of the code :
quiz.php file:
<?php
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
// Check user answer for previous question
if (isset($_POST['submit'])) {
if(isset($_SESSION['question_id'])){
$previous_question_id = (int) $_POST['question_id'];
// Query database
$getQuestion = "SELECT * from questions_table where id =
$previous_question_id";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
$correct = $row_get_question['correctAnswer'];
$selected_radio = $_POST['answer'];
if ($selected_radio == $correct)
echo "THAT ANSWER IS CORRECT";
$_SESSION['question_id'] = $previous_question_id +1;
$getQuestion = "SELECT * from questions_table where
(id=".$_SESSION['question_id'].")";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
else
echo "THAT ANSWER IS WRONG!";
}
}
if(!isset($_SESSION['question_id'])) {
$_SESSION['question_id']="0";
$getQuestion = mysql_query("SELECT * FROM questions WHERE
(id=".$_SESSION['question_id'].")";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
}
echo "<form action='quiz.php' method='post'>";
while($row = mysql_fetch_array($resultOfQuestion)){
echo " <b>" . $row['question'] . "</b>";
echo "<input type='radio' value='' name='answer' checked />";
echo $row['option1']; echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option2'];echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option3'];echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option4'];echo "<br />";
echo "<input type='submit' name='next' value='next' />";
}
I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>
I have a Database (MySQL) where is a table called: "dbtest" has the following fields,
id + v + o1 + o2 + o3 + o4 + g
to clarify that:
v: are the questions field
o1: the first answer
o2: the second
o3: third
o4: forth
g: is the right answer, where I put the number of the right answer for example, if I had a question with a correct answer "o3" the value of "g" should be "3"
(I did that myself thinking would be easier hopefully)
We yet did not reach the point I know, the thing is that I'm building a quiz program standing on the previous scheme, I made a page that calls the questions from the database and post them one below the other, the code was as the following:
<?php
include "config.inc";
$SQL = "SELECT * FROM test";
$query = mysql_query($SQL) or die();
echo "<form action=grade.php method=POST>";
while ($row = mysql_fetch_assoc($query)) {
echo "<p>$row[id]. ";
echo "$row[v]<br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o1]>$row[o1]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o2]>$row[o2]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o3]>$row[o3]</input><br>";
echo "<input type=radio name=answer[$row[id]] value=$row[o4]>$row[o4]</input><br>";
}
echo "<input type=submit name=submit value=Check>";
echo "</form>";
?>
The problem is when I wanted to write the "grade.php" page I fell off an edge, I absolutely lost, I could do it if there was just one question in the database, so no need to enter a loop, but since the database is expected to receive tons of question I lost control.
I was trying something like,
<?php
include "config.inc";
$SQL = "SELECT * FROM test";
$query = mysql_query($SQL) or die();
$n = 0;
while ($row = mysql_fetch_assoc($query)) {
$n++;
$ques[$n] = $_POST['answer'];
if ($ques[$n] == $row[g]) {
echo "<font color=green>Correct</font>"; }
else {
echo "<font color=red>Incorrect<br></font>"; }
}
?>
But did not make it, all what I need is to process the questions and give right/wrong answers, for every right answer (+1) for every wrong one (-1) then I will post the sum mathematically.
In HTML your have to change radio button :
No need to add </input>,
For value you set answer number,
Add quotes for attributes
echo '<input type="radio" name="'.$answer[$row['id']].'" value="1" />'.$row['o1'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="2" />'.$row['o2'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="3" />'.$row['o3'].'<br>';
echo '<input type="radio" name="'.$answer[$row['id']].'" value="4" />'.$row['o4'].'<br>';
In PHP :
You create some variables to store good and bad answers,
You check if value of $row['g'] is equal to answer number
$query = mysql_query("SELECT * FROM test") or die();
$good = 0; // Number of good answers.
$bad = 0; // Number of bad answers.
while ($row = mysql_fetch_assoc($query))
{
if ( $_POST['answer'][$row['id']] == $row['g'] )
{
echo '<span style="color: green;">Correct</span>';
$good++;
}
else
{
echo '<span style="color: red;">Incorrect</span>';
$bad++;
}
}