One quiz item per page (php/mysql quiz program) - php

I'm currently working on a quiz program using PHP/mySQL (my first time ever actually using either).
Up until now I was just working on getting it all functioning correctly with the mySQL tables, and to do so I was putting all questions in a quiz on one page. However, now I want to be able to put just one question per page and then progress by submitting one answer at a time.
The way my questions are chosen to be in the quiz may be a little confusing. They all have a "quiz_id" column that corresponds to the quiz they're in. The quiz has a "length" column that specifies how many questions it will actually have. So there can be more questions with the corresponding "quiz_id" than will actually be in the quiz. The way I randomly select which questions will be included is with "$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";".
Now I'm having a lot of trouble putting just one question per page. This is because each time you progress, the next random question needs to be chosen, as long as we haven't reached the limit of $length number of questions. A counter also needs to increase that keeps track of what number question you are on, out of how many ($length). I'm not sure if I need to have two separate action scripts.. one to begin the quiz, and then one to progress between questions.
Here's my quiz.php page (start page for any quiz):
<?php
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
// define the id and length from url
$id = mysql_real_escape_string($_GET['id']);
$length = mysql_real_escape_string($_GET['length']);
// query quiz table for all columns
$query_quiz = "SELECT * FROM quizzes WHERE id = '$id' LIMIT 1";
// if quiz query fails
if(!$query_quiz_result = mysql_query($query_quiz))
{
die("Couldn't run quiz query");
}
// fetch whole array of quiz info
$quiz = mysql_fetch_array($query_quiz_result);
//query question table for all columns
$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";
$q_result = mysql_query($question) or die ("couldn't run questions query");
// store queried questions as an array to pass via session variables
$q_array = array();
while($row = mysql_fetch_assoc($q_result))
{
$q_array[] = $row;
}
session_start();
$_SESSION['quiz'] = $id;
$_SESSION['questions'] = $q_array;
$_SESSION['length'] = $length;
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<!-- create the header using the quiz id and name -->
<h1 style="text-align: center;">Quiz <?php echo $quiz['id'] ?>: <?php echo $quiz['name'] ?></h1>
<hr />
<h4>This quiz will have a total of <?php echo $length?> questions.</h4>
<button onClick="parent.location='start.php'">Begin Quiz</button>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
And here's my start.php page.. not sure if I can use this one page for all the questions, or do I need a separate action page for once the quiz has begun and you're progressing past #1?
<?php
// continue the session
session_start();
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
$quiz_id = $_SESSION['quiz'];
$length = $_SESSION['length'];
$_SESSION['questions_array'] = $_SESSION['questions'];
$current_question = array_shift($_SESSION['questions_array']);
$_SESSION['counter'] = 1;
$counter = $_SESSION['counter'];
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<h3>Question <?php echo $counter ?> of <?php echo $length ?></h3>
<hr />
<h4><?php echo $current_question['prompt']?></h4>
<?php
// define query for answers for each question
$answers = 'SELECT `prompt` FROM `answers` WHERE `quiz` = '.$quiz_id.' AND `question` = '.$current_question['id'].'';
//if failed
if(!$answers_result = mysql_query($answers)){
die("Couldn't run answers query");
}
?>
<p style="margin-left: 50px;">
<?php
// if question type is "multiple choice", loop through answer choices and print them as options
if ($current_question['if_short_answer'] == 0) {
// loop through rows of answer choices
while($a_row = mysql_fetch_array($answers_result))
{
// print each answer choice
?>
<input type='radio' name='question_<?php echo $current_question['id']; ?>' value='<?php echo $a_row['prompt']?>'><?php echo $a_row['prompt']?>
<br />
<?php
}
echo "</p>";
}
// if question type is "short answer", create text box
elseif ($current_question['if_short_answer'] == 1) {
?>
<input type="text" name="question_<?php echo $current_question['id']; ?>" /><br />
</p>
<?php
} ?>
<?php
if ($counter >= 1) { ?>
<button onClick="parent.location='next.php'">Next Question</button>
<?php
}
else { ?>
<button onClick="parent.location='start.php'">Begin Quiz</button>
<?php
}
?>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
I apologize if this is a very vague or long question.. I've just gotten myself pretty lost now and not sure how to proceed. Basically I am asking: how can I put just one question per page, progressing through random questions until a limit of $length is reached, and then a "submit quiz" button at the end leads to a score page? All along the way, the "next question" button needs to store the user's input for the current question.
I basically need guidance in writing my script to progress from one question to the next.
Thanks!

All you need to get the all questions from Database, and using jquery show()/hide() method show only one questions at a time.
I had written sample script for your requirement here.
http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-and-twitter-bootstrap/

Firstly you are re creating the $q_array on each page so it will only contain the last displayed question which will not work
try
if(isset($_SESSION['questions']))
{
$_SESSION['questions']+= ", $question_id";
}
In the select query you should omit the questions with the already displayed in the array.

Related

How to get data from a MySQL database and insert it into text

I've been working on a website of mine- it's a shop for different items (it's also my first website). I just got done with the HTML/CSS part of the website but I want to make it more dynamic and easier to edit without having to change multiple pages at once. One way I figured I could do this and also make it easier to implement a website search is by having the names and prices of the items in a database and having PHP code retrieve the name and price and insert it underneath the image of the item. Unfortunately, I have absolutely no idea how to go about this. I've tried looking for other people with similar questions but none of them seem to be specifically what I'm looking for. I'll put my PHP code below and then I'll put some html code that shows where I want to put the information.
<?php
$servername = "localhost";
$username = "root";
$password = "testpw";
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
}
$sql = "SELECT id, name, price FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " .$row["id"]. " " .$row["name"]. " " .$row["price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So that's the PHP code that I use to get the information for each item. The problem though is that it gets the information for every item and displays it at once. I want the code to check for the ID of the item and then retrieve the stats about it and display them. This means if I want to rearrange items in the shop I only have to change the ID- which makes it much much easier for me to manipulate the shop and the items in it. Below is the HTML code for the items.
<div id="images">
<figure>
<img class="gunimage" id="(THIS IS THE ID USED TO GET THE INFO)" src="idk.png" width="225" height="190" alt="">
<figcaption><h3>Name: (INSERT NAME HERE USING PHP) </h3></figcaption>
<figcaption><h5>Price: (INSERT OTHER PRICE HERE)/month</h5></figcaption>
<figcaption><div id="tfbutton5"><form action="buy.html"><input type="submit" value="Rent" class="tfbutton5"></form></figcaption>
</div>
</figure>
</div>
I labeled where I want the info to go, and I want to have the ID thing so the PHP code knows what item it is. I know both codes work separately, as I've tested both of them many times. Sorry if my question is really long, I wanted to make it as specific as possible so it's clear what my problem is. Please excuse if my code requires a lot of changes to make applicable in the situation I'm describing, as I only could figure out how to make something that lists out the info for every item. Any help would be appreciated. Thank you.
If you wanted to do something more you could put in a file called
'connection.php' or something more descriptive
try {
$servername = 'localhost';
$username = 'root';
$password = 'testpw';
$dbname = 'testdb';
$db = new mysqli($servername, $username, $password, $dbname);
} catch(Exception $e) {
echo $e->error_list;
exit;
}
function execute_query($con, $query, $variables) {
$stmt = $con->prepare($query);
$stmt->execute($variables);
return $stmt;
}
you could split these the top part in a connection.php while the function in a function.php file if you have more than one function.
include ('connection.php');
$id_number = $_GET['id'];
# !! NOTICE if grabbing | my understanding another page |
// filter if grabbing from GLOBAL Variable $_GET
$id = filter_var($id_number, FILTER_SANITIZE_NUMBER_INT); //take out
if not grabbing from outside source.
$con = $db;
try {
$query = 'SELECT t.id as id , t.name as name, t.price as price
FROM items as t
WHERE t.id = :id';
$variables[':id'] = $id;
$items = execute_query($con, $query, $variables);
}catch(mysqli_error_list $e) {
echo $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="images"><!-- i am guessing you want it within this div-->
<?php if(isset($item)) { ?>
<?php foreach ( $items as $item) { ?>
<figure>
<img class="gunimage" id="<?php echo $item['id']; ?>"
src="idk.png" width="225" height="190" alt="<?php echo $item['name'];
?>">
<figcaption><h3>Name: <?php echo $item['name']; ?> </h3>
</figcaption>
<figcaption><h5>Price: <?php echo $item['price']; ?> </h5>
</figcaption>
<figcaption>
<!-- instead of a id tfbutton5 needs to be a class otherwise your
going to have an issue here when it loops, you will have an error-->
<div class="tfbutton5"><form action="buy.html"><input
type="submit" value="Rent" class="tfbutton5"></form>
<!--also, not sure why you have an Id and a class named exactly
identical but it is bad practice. sorry do not do it. -->
</figcaption>
</div>
</figure>
<?php } ?>
<?php } ?>
</div>
</body>
</html>
if you wanted an image source, you would need to enter that into a database and connect your Items table to an Image table with that table having say..rows id, image, and item-id. then use the item-id as a point between the item and the image

Making a column row that is empty from database table not appear in my quiz?

I'm trying to make it so that whenever there are empty cells in columns in my database table, they will not show up in my quiz application.
The way that the quiz is built up is that there are groups of four answers that share the same question ID (qid). When you press the next button you will get to see a set of four new questions and so on.
Right now there are empty spaces in quiz that are given a radiobutton on the side, How do I make it so that empty (answer) cells in my table column in mysql wont show up in my quiz?
My SQL table columns: qid(int), answers(varchar), points(int)
My code (PHP/HTML)
<html>
<head>
<meta charset="utf-8">
<script>
function goBack() {
window.history.go(-1);
}
</script>
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer IS NOT NULL && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' value="<?php echo $row1['Point'];?>"><?php echo $row1['answer'];?><br>
<?php
}
?>
<button type="button" onclick="history.back();">Tillbaka</button>
<input type='submit' name='forward' value='Nästa'>
</form>
</body>
</html>
In your SQL you have excluded results where the answer is NULL.
Is this how you are storing an empty answer field in your db table; as NULL?
If so you should not get any results for where the field 'answer' is set to NULL.
Maybe you are storing a string instead of NULL. You can use this code to see what is returned from an empty answer cell:
if($row['answer'] == '')
{
echo "Answer is an empty string.";
}
else if(is_null($row['answer'])){
echo "Answer is NULL value.";
}
else if($row['answer'] == "NULL")
{
echo "Answer is the string 'NULL'.";
}
At least now, you will know what the empty answer field in your table are being stored as, and then you can go about removing them from your quiz.
You could also use your Database Management System (PHPMyAdmin) to check how data is being stored.
Hope this Helps

Online Task Manager for website

Requesting some help on this task management system that i am making for class. I cant quite get it to work right. information is sometimes lost before it gets to the server and some of the last php code leeks thru to being seen on the site. can anyone tell me what i am doing wrong and help me to fix this? this code is supposed to allow you to send the task to a data base and the managing section relays the data from the database to the webpage.
data base is set up as this
3 Columns:
id - INT - 5 Length - Primary Key - AI.
description - VARCHAR - 255 Length.
active - BOOLEAN - 1 Length.
I am creating this on the hostica text editor that is within the site not an IDE if there are any discrepancy in the code
the website link is http://jtaylor84.net/taskmanager.php
I would like this code to work to take the information entered and relay it to the database and show in the managed tasks in order to have them up to be removed and show the tasks that have been entered.
<!DOCTYPE html>
<html>
<head>
<title>Online Task Manager</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect('localhost', 'root', '', 'Jhonny3_Task_Manager') or die(mysql_error());
if (isSet($_POST['createTask'])) {
if (isSet($_POST['desc']) && $_POST['desc'] != '') {
$desc = $_POST['desc'];
$q = mysqli_query($con, "INSERT INTO `tasks` VALUES ('', '$desc', '1')") or die(mysql_error());
if ($q) { echo 'Added task.';
}else
echo 'Failed to add task.';}}
if (isSet($_GET['removeTask']) && isSet($_GET['id'])) {
$id = $_GET['id'];
$q = mysqli_query($con, "UPDATE `tasks` SET `active`='0' WHERE `id`='$id'");
if ($q) { echo 'Task removed.';
}else
echo 'Failed to remove task.';}
?>
<h1>Add Task:</h1>
<form action='taskmanager.php' method='POST'>
Description of Task: <input type='text' name='desc'/>
<input type='submit' value='Create Task' name='createTask'/>
</form>
<h1>Manage Tasks:</h1>
<?php
$qu = mysqli_query($con, "SELECT * FROM `tasks` WHERE `active`='1'");
if (mysqli_num_rows($qu) > 0) {
after this section the code shows up on the web page and i am not sure why
while ($row = mysqli_fetch_array($qu)) {
echo "";
echo $row['description'];
echo "<a href='taskmanager.php?removeTask&id=".$row['id']."'>Remove Task</a>";
}
}
?>
<footer id="foot01"></footer>
</div>
<script src="sitescript.js"></script>
</body>
</html> `
Problem might be your php server .your code working fine in my server .

I have a code in which i want to display my data in the content using there ids stored in database

I m developing a website and here is my code, in my code i have two ids sId (section) and ssId (SubSectionId) and i have a page lets say index.php now I am making url like this -- when i click on the left navigation bar where i have links AND when i click on one link it sends an id like localhost/index.php?sId=29&ssId=0
Now i want to show ssId=181 data on the same page index.php using there ids by taping the same leftnav of the subsection which sends an id localhost/index.php?sId=29&ssId=181
The issue here is that the result is showing on the contentarea of sId=29 instead of ssId=181 and both are stored in database..
if(isset($_GET['sId']) && !empty($_GET['sId']))
{
?>
<div>
<br /><br />
<h2 class="heading">
<?php
$sId = intval($_GET['sId']);
$qry = "SELECT `SectionId`,`Title`,`Details` FROM `section` WHERE `SectionId` = $sId";
$records = mysql_query($qry);
while($record= mysql_fetch_array($records))
{
echo $record['Title'];
?>
</h2>
<br />
<p>
<?php
echo $record['Details'];
}
?>
</p>
</div>
</div>
<?php
}
elseif(isset($_GET['sId']) && !empty($_GET['sId']) && isset($_GET['ssId']) && !empty($_GET['ssId']))
{
?>
<div>
<br /><br />
<h2 class="heading">
<?php
$sId = intval($_GET['sId']);
$ssId = intval($_GET['ssId']);
$qry = "SELECT SubSectionId,Title,Details FROM `pages` WHERE `SubSectionId` = $ssId";
$records = mysql_query($qry);
while($record= mysql_fetch_array($records))
{
echo $record['Title'];
?>
</h2>
<br />
<p>
<?php
echo $record['Details'];
}
?>
</p>
</div>
</div>
<?php
}
}
Hope you guys understand. Thanks in advance.
If I understand you correctly, you're saying the following.
Your script expects an sid and/or and ssid as input.
If either is supplied, your script will load the relevant content from the DB and show it
But, currently your script does not show content of the ssid and will only show the content of the sid
Am I right?
Try using two IF blocks rather than an IF/ELSE. This will make sure that all conditions that are met will be run rather than just one.
Also, you can stick to using the just the empty function call.
if ( !empty($_GET['sId']) ) {
//load and show content for section
}
if ( !empty($_GET['ssId']) ) {
//load and show content for sub section
}
UPDATE - To give subsections precedence over sections, you'll need to reverse your IF/ELSE condition.
if ( !empty($_GET['sId']) && !empty($_GET['ssId']) ) {
//load and show content for sub section if availavle
} else if ( !empty($_GET['sId']) ) {
//load and show content for section
}

GET POST mysql data on next page

Ok, I haven't done much of this sort of stuff, so I am clueless right now.
On the first page you hit the form submit that generates a bunch of information/stuff and displays it underneath submit button, but I don't know how to take the displayed information and use it on the next page I will show some of my code. btw I know the code is bad, just ignore that fact.
<form name="input" action="slaymonster.php" method="post" id="id">
<div align="center">
<input name="Submit" id="Submit" type="submit" class="button" value="Explore Map!"/>
</div>
</form>
if (isset($_POST['Submit'])) {
include 'includes/mapstuff.php';
// So here we pick a random row from the table pokemon notice the order by rand
$sql23 = "SELECT * FROM map1pokemon ORDER BY RAND() LIMIT 1;";
// We then check for errors
$result23 = mysql_query($sql23) or die(mysql_error());
// we then make the result into a virable called battle_get23
$battle_get23 = mysql_fetch_array($result23);
$sql2 = "SELECT * FROM pokemon WHERE name='".$battle_get23['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
// Now we need to make sure the image is safe be for we use it
$pic2= mysql_real_escape_string($battle_get2['pic']);
$pic = strip_tags($pic2);
include 'includes/maptypes.php';
?>
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
<p></p>
<?php
echo "You have just found a " ;
echo $randomview97[0];
echo " ";
echo $battle_get23['pokemon'];
$_SESSION['pokemon'] = $battle_get23['pokemon'];
$_SESSION['type'] = $randomview97[0];
$_SESSION['pic'] = $battle_get2;
$_SESSION['money'] = $randomview2[0];
$_SESSION['level'] = $randomview3[0];
$_SESSION['ticket'] = $randomview4;
?>
<p></p>
<?php
echo "You have gained ".$randomview3[0]." levels" ;
echo " ";
?>
<p></p>
<?php
echo "You have received $".$randomview2[0]."" ;
echo " ";
?>
<p></p>
<?php
echo "</center>";
}
?>
it displays the pokemon's picture it's name, type,amount of money you got ect...
I need all that information to be useable on the next page.
Any help is appreciated :)
At the top of your PHP code, be sure to include session_start();
You are already using session variables, so you should refer here to see what a PHP session is: PHP session_start() - Manual. It makes sure to do exactly what you are asking for (someone may point out that in certain cases session_start(); is not necessary, but for your purposes, while learning, stick to the Manual for best practices)
This information will be usable on the next 'page', just as the manual describes, and will be available, until you call something like session_destroy().
If you want to pass the information from one page to another. You have to put the result inside the form tag. Then it is possible to pass the information to another page. Or you can put it on the session and get information from any page.
you got my point? If you explain what you want to do. Then I will do something for you.

Categories