I'm doing a program where I have several exercises with their id (e.g. Id = 1, 2, 3 ...) What I would like to do is that once the user is in an exercise, he can press the Next button and take him to the next exercise, for example id + 1.
Below I show what I've done. Can you help me?
This is my modified question, now it works:
<?php
include_once("functions.php");
// Start the session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
/*echo*/ $id=$_GET['id']; // Current question
$sql = "SELECT * FROM exercises where exercise_id='$id'";
$result = $conn->query($sql); /*Check connection*/
$question_ids = [];
$result2 = doSearch($conn, 'exercise_id');
while($row = $result2->fetch_assoc()) {
array_push($question_ids, $row["exercise_id"]);
}
$order = $_GET['order'];
$next_question_id = -1;
$next_question_order = $order + 1;
if (count($question_ids) >= $next_question_order) {
$next_question_id = $question_ids[$order];
}
?>
<div id="centered_B" class="header">
<?php
$row = $result->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"]?>"><br/><br/>
<form action='' method='post'>
<input type="radio" name="choice" value= "1" /><img src="<?php echo $row["image_path_A"] ?>"/><br>
<input type="radio" name="choice" value= "2" /><img src="<?php echo $row["image_path_B"] ?>"><br>
<input type="radio" name="choice" value= "3" /><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p2>Select difficulty level:</p2>
<form action='' method='post'>
<select name="choose" id="choose">>
<option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
<option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
<option value="3" <?php if($row["difficulty"]=="3") { echo "selected"; } ?> >3</option>
<option value="4" <?php if($row["difficulty"]=="4") { echo "selected"; } ?> >4</option>
<option value="5" <?php if($row["difficulty"]=="5") { echo "selected"; } ?> >5</option>
</select>
<br><br><br>
<input class="buttonSubmit" type="submit" name="submit" value="Submit">
<?php
if ($next_question_id >= 0) {
?>
<a href="?id=<?php echo $next_question_id; ?>&order=<?php echo $next_question_order; ?>" class="buttonNext" >Next Question</a>
<?php
}
?>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
$user_id = $_SESSION['user_id'];
$user_check_query = "SELECT * FROM users WHERE id='$user_id'";
if(isset($_POST['choice'], $_POST['choose'])){
$choice_answer=$_POST['choice'];
$difficulty=$_POST['choose'];
// */$user_id = $_SESSION['user_id'];*/
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES ('$id','$user_id', '$difficulty', '$choice_answer')";
$sql=mysqli_query($conn,$query);
}
}
?>
Not sure what your JS or PHP level is, but here's a pure PHP solution - not using JS.
Things to notice:
Using PDO parameterized queries to secure against SQL injection
Using a hidden form field to pass around the current question ID. After the user submits, we insert their response in the DB, and then redirect to the next question by incrementing $id++
You had 2 <form> tags. I removed one.
Please note, this code is not tested. Let me know if you have any questions. Good luck!
<?php
session_start();
// Using PDO instead of mysqli. Nothing wrong with mysqli but I'm more comfortable with PDO.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// This is your connection to the DB.
$pdo = new PDO($dsn, $user, $pass, $opt);
// This is the current question being displayed to the user.
$id = $_GET['id'];
// You should probably do some validation on $id here. Should it be numeric, not null etc.
// Notice that we're using ? instead of passing the value directly to the DB. This is called prepared statements.
// https://phpdelusions.net/pdo#prepared
$stmt = $pdo->query('SELECT * FROM exercises where exercise_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// You should also validate the $row here. Did you actually find a question from the DB?
?>
<div id="centered_B" class="header">
<p><?php echo $row["exercise_id"] . ". " . $row["text"] ?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"] ?>"><br/><br/>
<!-- Changed the method to GET -->
<form action="" method="GET">
<!-- Notice that we're passing the question ID to server when the form submits. -->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<label>
<input type="radio" name="choice" value="1"/>
</label><img src="<?php echo $row["image_path_A"] ?>"/><br>
<label>
<input type="radio" name="choice" value="2"/>
</label><img src="<?php echo $row["image_path_B"] ?>"><br>
<label>
<input type="radio" name="choice" value="3"/>
</label><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p>Select difficulty level:</p>
<label for="choose"> Difficulty
<select name="choose" id="choose">>
<option value="1" <?php if ($row["difficulty"] == "1") {
echo "selected";
} ?> >1
</option>
<option value="2" <?php if ($row["difficulty"] == "2") {
echo "selected";
} ?> >2
</option>
<option value="3" <?php if ($row["difficulty"] == "3") {
echo "selected";
} ?> >3
</option>
<option value="4" <?php if ($row["difficulty"] == "4") {
echo "selected";
} ?> >4
</option>
<option value="5" <?php if ($row["difficulty"] == "5") {
echo "selected";
} ?> >5
</option>
</select>
</label>
<br><br><br><!--- Button --->
<!-- <button class="buttonSubmit" >Submit</button>-->
<input type="submit" name="submit" value="Submit">
<button class="buttonNext">Next Question</button>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
// Changed to a single if-statement
if (isset($_POST['choice'], $_POST['choose'])) {
$user_id = $_SESSION['user_id'];
$choice_answer = $_POST['choice'];
$difficulty = $_POST['choose'];
// Again, using prepared statements.
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES (?, ?, ?, ?)";
$pdo
->prepare($query)
->execute([$id, $user_id, $difficulty, $choice_answer]);
// Redirect to self with incremented question ID.
// https://stackoverflow.com/a/8131377/296555
header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $id++);
die;
}
}
Maybe this can help you:
var i=$_GET['id']){;
function getNext()
{
var = var + 1; //increase var by one
return var;
}</script>
<button class="buttonNext" onclick="getNext" >Next Question</button>
Uhm, I don't know where to start here...
Ok, for first your code is horrible - regarding in style, security and everything - sorry ;)
But to help with your problem:
Don't access the next id directly but go by
SELECT * FROM exercises WHERE exercise_id > $currentId ORDER BY exercise_id ASC LIMIT 0,2
This will help if you want to delete an exercise at some point, so have a gap like 1,2,4 (3 was deleted). You can also create a position field to sort the order of the question manually, but I guess that's too advanced for first.
However:
On start you check if there's a $_GET['id'] param and set this to $currentId. Best by $currentId = (int)$_GET['id'] to prevent a serious injection. If no GET param is there, set $currentId = 0 (first call then).
Then you run the query to get your exercise - it will be in the first row of the result.
On HTML side you just assign the exercise_id from the database result to the link which leads on the next exercise (so no JavaScript is required).
To test, if there's a next question at all check if a second row exists in the result (that's why LIMIT 0,2 instead of 0,1) to decide if to show the "next exercise button".
Related
I have 2 lists - master and category. When moving items from master list to category list I can save category list with new values but unable to save master list with removed items. I was thinking of means of reading master list into hidden field of category list but not sure how to go about. Need help with this and herewith my code:-
<select name=master[] id=master class="master" multiple="multiple" size='6'>
<?php
$file = fopen("master.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$master = $row[0];
?>
<option value="<?php echo $master;?>"><?php echo $master; ?></option>
<?php
}
?>
</select>
<form action="" method="post">
<input type=button class="master" name=b1 id=b1 value='Move >'>
<input type=button class="master" name=b2 id=b2 value='< Remove'>
<select name=category[] id=category multiple="multiple" class=master>
<?php
$file = fopen("category.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$category = $row[0];
?>
<option value="<?php echo $category;?>"><?php echo $category;?></option>
<?php
}
?>
</select>
<input type="submit" value="Save File" name="submit">
</form>
The move and remove function works so I am not including it but here is my js for writing to csv file.
<?php
if ($_POST['master']) {
$master = $_POST['master'];
foreach ($master as $key => $value) {
$result.=$value. "\n";
}
file_put_contents('master.csv',$result);
}
if ($_POST['category']) {
$category = $_POST['category'];
$categoryunique = array_unique($category);
sort($categoryunique);
foreach ($categoryunique as $key => $value) {
$result.=$value. "\n";
}
file_put_contents('category.csv',$result);
}
?>
This is what my code does: when a username is typed in the #type input field, and if that typed value matches a row value from my database table users, then my jquery code will come to action. My jquery code will then reveal the hidden div that contains text of that typed in username. My problem is my current code ignores other typed in usernames, and for some reason will reveal only one username. Example of my issue:
allen <-- "allen" is typed in input field
--------
[allen] <-- hidden div for allen now shows
pete
-------- <-- "pete" is typed in input field
<-- but hidden div for pete does not show. Why?
Is this an event bubbling issue with my js code? Because I did add e.propagation but it didn't do anything. How would I rewrite my current code so that any username that is typed will reveal a hidden div for it. Because currently I'm only able to get a hidden div for "allen" but not for the rest of the usernames. Please help, here is my code:
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var userid = '<?php echo $userid; ?>';
if (this.value == $("#username"+userid).attr('value')) {
$("#border"+userid).css("display", "block");
}
else {
$("#border"+userid).css("display", "none");
}
});
Sql code:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$userids[] = $row['userid'];
$usernames[] = $row['username'];
}
$stmt->close();
#MohammadBagheri - Output for code below:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo '<pre>'.print_r($row, 1).'</pre>';
}
$stmt->close();
Output:
Array
(
[userid] => 35
[username] => pete
)
Array
(
[userid] => 44
[username] => allen
)
I know what the problem is.
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var username = $(this).val();
var userid = $("input[value='"+username+"']").attr("id");
$("div[id^=border]").css("display", "none");
$("#border"+userid).css("display", "block");
});
You have been selecting the userid of the last occurrence of the loop and set that in jquery code which means it will always show the user with that user id and not checking what you input.
Please let me know if you need more help.
I am trying to get the value of the selected option from my select. And I am trying to see it's output through a javascript echo. Here's what I've got so far. I am not getting the value
<form method="post" action="">
<select class="form-control" name="empSel" id="empSel">
<?php
$sql2 = "SELECT * FROM employee";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row2 = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row2['lastname'] ?>"><?=
/*$row2['user_surname']." ".*/
$row2['id']."-".$row2['lastname'] ?></option>
<?php
}
?>
</select>
<Label> Confirm</Label>
<div class="form-group col-md-6">
<input type="submit" class="btn btn-block btn-info"
name="submit"/>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$userid = $_POST['empSel'];
echo '<script type="text/javascript"> alert('.$userid.')</script>';
$userid = preg_replace('/\D/', '', $userid);
$sql2 = "SELECT * FROM employee where id ='userid'";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row = mysql_fetch_assoc($result)) {
echo '<script type="text/javascript"> alert("")</script>';
}
}
?>
An javascript alert doesn't pop out on this code. However, when I switch the value in the echo to a different variable an alert pops up. What does it mean? Do I properly get the value of my select and the page refreshed instantly that I didn't get to see it? Thanks
Edit:
An example of the option value would be 1-Lastname
And here's what I've tried.
<?php
if (isset($_POST['empSel'])){
$userid = $_POST['empSel'];
$userid = intval($userid);
echo '<script type="text/javascript"> alert('.$userid.')</script>';
}
?>
Now the javascript alert shows, but it echo 0. I think I am still not getting the value of my selected option
<option value="<?php echo $row2['id'] ?>">
This fixed it. In my previous code the option value was the surname...
I am stuck in getting value from drop down. Drop down is dynamically filled from sql server database.
Dropdown 1 displays product name and it is dynamically filled.
Dropdown 2 displays environment name and it is filled by HTML.
I am getting value of environment but not product.
Please help me. Thanks
Here is the code:
<form action="" method="post">
//Dropdown 1
<p>Product Name:
<select name="productname">
<option value="">Select</option>
<?php
if( $conn )
{
$sql_dd = "SELECT ProductName from Product";
$stmt = sqlsrv_query( $conn, $sql_dd );
if( $stmt === false) {die( print_r( sqlsrv_errors(), true) );}
$rows = sqlsrv_has_rows( $stmt );
if ($rows === false)
echo "There is no data. <br />";
else
{ while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
echo "<option value=''>".$row['ProductName']."</option>";
}
}
?>
//Dropdown 2
Client Type:
<select name="environment" style="width: 10%;">
<option value="">Select</option>
<option value="en1">en1</option>
<option value="en2">en2</option>
<option value="en3">en3</option>
</select>
<input type="submit" class="theme-btn" value="Search" name="submit"/>
<?php
if(isset($_POST['submit']) )
{
$productname = $_POST['productname'];
$environment= $_POST['environment'];
echo "productname: ".$productname." environment: ".$environment;
}?>
The value is not added
this:
echo "<option value=''>".$row['ProductName']."</option>";
should be
echo "<option value='" . $row['ProductName'] . "'>". $row['ProductName'] ."</option>";
I want to make a multiple choice and the question is coming from database. I am sure that my database name is correct, but when i click next, the question is not changing, it is directly going to the end/result of question and the question is not random too. The last question that I inserted into the database is displayed in webpage. Please help
this is my code:
<?php
require_once('includes/db_conn.php');
$query = "select * from question";
$query_result = $dbc->query($query);
$num_questions_returned = $query_result->num_rows;
if ($num_questions_returned < 1){
echo "There is no question in the database";
exit();}
$questionsArray = array();
while ($row = $query_result->fetch_assoc()){
$questionsArray[] = $row;
}
$correctAnswerArray = array();
foreach($questionsArray as $question){
$correctAnswerArray[$question['question']] = $question['correct_answer'];
}
$questions = array();
foreach($questionsArray as $question) {
$questions[$question['question']] = $question['question'];
}
$choices = array();
foreach ($questionsArray as $row) {
$choices[$row['question']] = array($row['wrong_answer1'], $row['wrong_answer2'], $row['wrong_answer3'], $row['correct_answer']);
}
error_reporting(0);
$address = "";
$randomizequestions ="yes";
$a = array(
1 => array(
0 => $question['question'],
1 => $row['wrong_answer1'],
2 => $row['wrong_answer2'],
3 => $row['wrong_answer3'],
4 => $row['correct_answer'],
6 => 4
),
);
$max=1;
$question=$_POST["question"] ;
if ($_POST["Randon"]==0){
if($randomizequestions =="yes"){$randval = mt_rand(1,$max);}else{$randval=1;}
$randval2 = $randval;
}else{
$randval=$_POST["Randon"];
$randval2=$_POST["Randon"] + $question;
if ($randval2>$max){
$randval2=$randval2-$max;
}
}
$ok=$_POST["ok"] ;
if ($question==0){
$question=0;
$ok=0;
$percentage=0;
}else{
$percentage= Round(100*$ok / $question);
}
?>
<HTML><HEAD>
<SCRIPT LANGUAGE='JavaScript'>
<!--
function Goahead (number){
if (document.percentaje.response.value==0){
if (number==<?php print $a[$randval2][6] ; ?>){
document.percentaje.response.value=1
document.percentaje.question.value++
document.percentaje.ok.value++
}else{
document.percentaje.response.value=1
document.percentaje.question.value++
}
}
if (number==<?php print $a[$randval2][6] ; ?>){
document.question.response.value="Correct"
}else{
document.question.response.value="Incorrect"
}
}
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=FFFFFF>
<CENTER>
<H1><?php print "$title"; ?></H1>
<TABLE BORDER=0 CELLSPACING=5 WIDTH=500>
<?php if ($question<$max){ ?>
<TR><TD ALIGN=RIGHT>
<FORM METHOD=POST NAME="percentaje" ACTION="<?php print $URL; ?>">
<BR>Percentaje of correct responses: <?php print $percentage; ?> %
<BR><input type=submit value="Next >>">
<input type=hidden name=response value=0>
<input type=hidden name=question value=<?php print $question; ?>>
<input type=hidden name=ok value=<?php print $ok; ?>>
<input type=hidden name=Randon value=<?php print $randval; ?>>
<br><?php print $question+1; ?> / <?php print $max; ?>
</FORM>
<HR>
</TD></TR>
<TR><TD>
<FORM METHOD=POST NAME="question" ACTION="">
<?php print "<b>".$a[$randval2][0]."</b>"; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="1" onClick=" Goahead (1);"><?php print $a[$randval2][1] ; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="2" onClick=" Goahead (2);"><?php print $a[$randval2][2] ; ?>
<?php if ($a[$randval2][3]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="3" onClick=" Goahead (3);"><?php print $a[$randval2][3] ; } ?>
<?php if ($a[$randval2][4]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="4" onClick=" Goahead (4);"><?php print $a[$randval2][4] ; } ?>
<BR> <input type=text name=response size=8>
</FORM>
<?php
}else{
?>
<TR><TD ALIGN=Center>
The Quiz has finished
<BR>Percentage of correct responses: <?php print $percentage ; ?> %
<p>Home Page
<?php } ?>
</TD></TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
this is my process add data to database:
<?php
include('includes/header.html');
error_reporting(-1);
ini_set('display_errors', 'On');
//Check for empty fields
if(empty($_POST['question'])||
empty($_POST['correct_answer']) ||
empty($_POST['wrong_answer1']) ||
empty($_POST['wrong_answer2']) ||
empty($_POST['wrong_answer3']))
{
echo "Please complete all fields";
exit();
}
//Create short variables
$question = $_POST['question'];
$correct_answer = ($_POST['correct_answer']);
$wrong_answer1 = ($_POST['wrong_answer1']);
$wrong_answer2 = ($_POST['wrong_answer2']);
$wrong_answer3 = ($_POST['wrong_answer3']);
//connect to the database
require_once('includes/db_conn.php');
//Create the insert query
$query = "INSERT INTO question VALUES ('$question', '$correct_answer', '$wrong_answer1','$wrong_answer2','$wrong_answer3')";
$result = $dbc->query($query);
if($result){
echo "Your quiz has been saved";
} else {
echo '<h1>System Error</h1>';
}
$dbc->close();
?>
Your first mistake is making array of $a why are you not using $choices which you had made in last for loop and for random questions handle $choices array and your submit button of next is outside the form so you will not get form values on next button.take it inside the form tag.
Another thing is on radio button click don't write anything just write your function on submit click event and then handle the next question after saving the previous answer.
These are what my suggestions.. for more help put here your database back up and its connected files so that I can help you in coding.