How get 1 question and 4 answers from this script? - php

I am creating a webGL game on Unity but want to get my php correct first.
I have 2 tables questions and answers. Each question has 4 potential answers and need to pull these from my db.
The answer table matches with the question table through questionId.
Questions:
Should I better use a table join or should I separate them?
Should I simply have a select statement just for the question table then a
join table for answers and submit separately?
Should I have created
the answer table with 4 columns for different answers?
Current code:
<?php
$query = ("select questiontable.questionId, questiontable.question, answertable.answerId,answertable.answer, answertable.questionId, questiontable.scoreValue
FROM questiontable
inner join answertable on questiontable.questionId=answertable.questionId ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
echo $row ['question'];
echo $row ['answer'] ;
echo $row ['answer'] ;
echo $row ['answer'];
echo $row ['answer'];
}
?>
Here are my tables:
CREATE TABLE `braingain`.`questionTable`
( `questionId` INT NOT NULL AUTO_INCREMENT , `question` VARCHAR(600) NOT NULL , `scoreValue` INT NOT NULL , `subject` VARCHAR(50) NOT NULL , PRIMARY KEY (`questionId`));
CREATE TABLE `braingain`.`answerTable`
( `answerId` INT NOT NULL , `answer` VARCHAR(600) NOT NULL , 'questionId', isCorrect;
The query should pull questions and 4 associated answers into an array.
Desired result
The created array should look like this:
| question | answerA | answerB | answerC | answerD |
| WHICH IS THE CORRECT SPELLING? | APPLE | APEL | APPUL | APPAL |

Run two nested queries,
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD');
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = ". $row ['questionId'] order by answerId);
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
while ($row2 = mysqli_fetch_assoc($result2)){
$output[answer_array[$i]]=$row2['answer'];
$i++;
}
}
print_r($output);
?>

Please have a look at indentation, makes code much more plesant :)
<?php
$query = ("
SELECT
questiontable.questionId,
questiontable.question,
answertable.answerId,
answertable.answer,
answertable.questionId,
questiontable.scoreValue
FROM
questiontable
INNER JOIN
answertable on questiontable.questionId = answertable.questionId
ORDER BY RAND()
LIMIT 1
");
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$data = [];
$data[] = null;
$keys = [
'question',
'answerA',
'answerB',
'answerC',
'answerD',
];
$return = [];
while ($row = mysqli_fetch_assoc($result)){
if ($data[0] !== $row['question']) {
$data = [];
$data[] = $row['question'];
}
$data[] = $row['answer'];
if (count($data) === 5) {
$dataAssociative = array_combine($keys, $data);
$return[] = $dataAssociative;
}
}
var_dump($return);
?>

ok, so i have everything working with my php etc. i have it echoing the result as i want heres the code...
<?php
session_start();
include 'dbconnect.php';
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD'); //loads answers into array
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");//sql query to get questions
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = '". ($row ['questionId'])."' order by rand()");//sql query to get answers for questions by questionId
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
$question=$row ['question'];
while ($row2 = mysqli_fetch_assoc($result2)){
$output[$answer_array[$i]]=$row2['answer'];
$i++;
$_POST = $output;
}
}
echo "</br> ";
echo $_POST ['question'];
echo "</br> ";
echo $_POST['answerA'];
echo "</br>";
echo $_POST['answerB'];
echo "</br>";
echo $_POST['answerC'];
echo "</br> ";
echo $_POST['answerD'];
?>
now i need to store the results in unity so i can assign them to buttons etc.
i have it pulling the details but unsure how to assign for example $_POST['answerA]; to a variable in c#.
this is my c# code...
public class qNaDisplay : MonoBehaviour {
public Text questionDisplayText, answerAText, answerBText, answerCText, answerDText;
public Text questMessage, answerMessage;
private string question, a, b, c, d;
// Use this for initialization
void Start ()
{
WWW questionURL = new WWW("http://localhost:8080/Project/PHP/questionRequest.php");
question = questionDisplayText.text;
a = answerAText.text;
b = answerBText.text;
c = answerCText.text;
d = answerDText.text;
StartCoroutine(qNaget(questionURL));
}
// Update is called once per frame
void Update () {
}
private IEnumerator qNaget (WWW questionURL)
{
yield return questionURL;
Debug.Log(questionURL.text);
if (questionURL.error != null)
{
print("There was an error getting the question " + questionURL.error);
}
else
{
Debug.Log (questionURL.text); // this is a GUIText that will display the scores in game.
}
}
}

Related

Display question with 3 options for quiz with PHP

So I am working on a project where I have a database filled with questions/options. Each question has 3 options (1 of them is right).
Before a user starts a quiz he selects how many questions he wants to have. I do this with a select form. PHP then sends value from select form to the quiz page. Where it's used in SQL query:
SELECT *
FROM quiz_question
WHERE quiz_id = 1
ORDER BY RAND()
LIMIT $number
The $number stands for value of select form
I can display questions but not options for the selected question.
My code:
<div id="quiz">
<?php
$number = $_POST['number'];
$sql = "SELECT *
FROM quiz_question
WHERE quiz_id = 1
ORDER BY RAND()
LIMIT $number";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<p>";
echo $row['question'];
echo "</p>";
}
}
?>
</div>
My database looks something like this:
quiz
id (PK)
quiz_name (text)
quiz_question
id (PK)
quiz_id (FK)
question (text)
quiz_question_option
id (PK)
quiz_question_id (FK)
quiz_option (text)
is_correct (enum 0, 1)
EDIT:
I tried to use INNER JOIN but when I used ORDER BY RAND() and LIMIT I couldn't get all 3 options for a single question.
Just put aside SQL injection issue (you should use prepared statement), here is how you can use a secondary query to get all the options of the quiz for rendering.
<div id="quiz">
<?php
// aggregate an array of options
$option_results = mysqli_query($conn, "SELECT qo.* FROM quiz_question_option qo
LEFT JOIN quiz_question q ON (qo.quiz_question_id = q.id)
WHERE q.quiz_id = 1");
$options = [];
while ($option = mysqli_fetch_assoc($option_results)) {
$options[$option['quiz_question_id']] = $option;
}
mysqli_free_result($option_results);
$number = $_POST['number'];
$sql = "SELECT * FROM quiz_question WHERE quiz_id = 1 ORDER BY RAND() LIMIT $number";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0)
{
while ($question = mysqli_fetch_assoc($result)) {
echo "<p>";
echo $question['question'];
echo "</p>";
}
if (isset($options[$question['id']])) {
echo "<ul>";
foreach ($options[$question['id']] as $option) {
echo $option['quiz_option'];
}
echo "</ul>";
}
}
?>
</div>
Now, to convert to prepared statements:
<div id="quiz">
<?php
$number = $_POST['number'] ?? 10000;
$quiz_id = 1;
// aggregate an array of all questions' options of a quiz
$option_stmts = mysqli_prepare($conn, "SELECT qo.* FROM quiz_question_option qo
LEFT JOIN quiz_question q ON (qo.quiz_question_id = q.id)
WHERE q.quiz_id = ?");
$option_stmts->bind_param('i', $quiz_id);
$option_results = $option_stmts->execute();
$options = [];
while ($option = mysqli_fetch_assoc($option_results)) {
$options[$option['quiz_question_id']] = $option;
}
mysqli_free_result($option_results);
mysqli_stmt_close($option_stmts);
// query for all the questions of a quiz
$stmt = mysqli_prepare($conn, "SELECT * FROM quiz_question WHERE quiz_id = ? ORDER BY RAND() LIMIT ?");
$stmt->bind_param('ii', $quiz_id, $number);
$result = $stmt->execute();
if (mysqli_num_rows($result) > 0)
{
while ($question = mysqli_fetch_assoc($result)) {
echo "<p>";
echo $question['question'];
echo "</p>";
}
if (isset($options[$question['id']])) {
echo "<ul>";
foreach ($options[$question['id']] as $option) {
echo $option['quiz_option'];
}
echo "</ul>";
}
}
?>
</div>

How do I get multiple results from different rows in a table?

I am trying to get all the rows of results from my table 'question' where the quiz ID ($currentQuizID) is the same. My code only allows me to get a single row of data from the table, so what should I do?
$findQuiz = "SELECT QuizID FROM quiz ORDER BY QuizID DESC";
$result = mysqli_query($user->db,$findQuiz);
$iddata = mysqli_fetch_array($result);
$currentQuizID = $iddata['QuizID'];
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata2 = mysqli_fetch_array($result2);
echo $iddata2[0];
echo $iddata2[1];
echo $iddata2[2];
Add this:
while($row = mysqli_fetch_array($result2)) {
echo $row["Type"]." ".$row["Question"]." ".$row["Answer "]."\n";
}
After getting Quiz id's Use while loop to get multiple records from question's table
$findQuiz = "SELECT QuizID FROM quiz ORDER BY QuizID DESC";
$result = mysqli_query($user->db,$findQuiz)
$totalArray = array();
while($iddata = mysqli_fetch_array($result);)
{
$currentQuizID = $iddata['QuizID'];
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata2 = mysqli_fetch_array($result2);
$res['Type'] = $iddata2[0];
$res['Question'] = $iddata2[1];
$res['Answer'] = $iddata2[2];
array_push($totalArray,$res);
}
print_r($totalArray);
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata_questions = array();
while($row = mysqli_fetch_array($result2)) {
$iddata_questions[] = array($row["Type"],
$row["Question"],
$row["Answer"]);
}
echo "<pre>";
var_dump($iddata_questions);
echo "</pre>;

SQL - Displaying names instead of ID [duplicate]

This question already has answers here:
Select Name instead OF ID in table with ID-Ref Column SQL
(2 answers)
Show Name Instead of ID from Different Table
(2 answers)
Closed 1 year ago.
I have 2 tables
rankID | name
1 | new
2 | learner
3 | experienced
4 | pro
And another with all the user info and passwords and stuff
id | username | rankID
1 | hello | 3
2 | hey | 3
I have come so far so I can display their rank number, but I want to display the rank name. How can I do that? I have tried a lot of things but I'm not so good at sql and the php part of it.
This is the code I use to display the rank number
//Get rankID
$query = "SELECT rankID FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
And to display the rank number:
Rank: <?php echo $rank; ?>
Simple JOIN query :-
"SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'"
And then After:-
$query = "SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
Do:-
$rank = $row['rankID'];
$rank_name = $row['rank_name'];
Rank: <?php echo $rank; ?>
RankName: <?php echo $rank_name; ?>
Or
$rank_data = $row;
Rank: <?php echo $rank_data['rankID']; ?>
RankName: <?php echo $rank_data['rank_name']; ?>
Not:- lot of other possible ways are there which are listed by other programmers in comment and answer as well.
//Get datas
$query = "SELECT rankID, name FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
$rank = $row['name'];
And to display the datas:
Rank: <?php echo $rank; ?>
Name: <?php echo $name; ?>
Hope so this should make a trick for you.
$query = "SELECT rankID FROM users WHERE id = '".$userId."'";
$result = $conn->query($query);
$count = $result->num_rows;
if($count==0)
{
return false;
}
else
{
$rows=[];
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
Please use below code
$query = "SELECT name FROM users as u JOIN rank as r ON r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
Name: <?php echo $name; ?>
When you want to get data from two different table.You need join query.
Here is your query which will solve your proble definitely :
$q="select a.name,b.rankID from rankname as a INNER JOIN user as b
ON a.rankID = b.rankID";
For more know about How to join two tables see this:http://www.tutorialspoint.com/sql/sql-using-joins.htm
Hope this will help you better.
Please try this
//Get rankID
$query = "SELECT r.name as rank_name FROM rank as r inner join users as u on r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo 'Rank: '. $rank;
try this:
//Get rankID
$query = "SELECT rankID, rank.name AS rank_name FROM rank, users WHERE id = '$userId' and users.rankid = rank.rankid";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo $rank;

INSERT MySQL query not executing properly using PHP

I'm currently making a graduation website for my school where grads are supposed to submit a comment as well as submit votes for a poll.
The database has 4 tables, one for the student information, one for questions, one for comments which has a foreign key referencing snum from students and one for the poll(called survey) which has 2 foreign keys, one referencing snum again and one referencing the question id.
This is the code my seniors left for me. What it's supposed to do is create blank rows in the comments and survey tables to be updated later. However what it actually does is send everything in the comment table twice (so if there were 300 students, I would end up with 600 rows in the comments table and 0 in the survey table)
I'm still quite new to MySQL and PHP and only learned it about a month ago. If anyone can help or suggest a better way of approaching this, it would be much appreciated.
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++)
{
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('{$snum[$i]}' , NULL);";
$result = mysqli_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('{$snum[$i]}', {$qid[$a]}, NULL, NULL);";
$result = mysqli_query($link,$sql_query);
}
}
UPDATE 1:I think I found what the problem is. When I try to output $qid[$a], I get a null value. In the table, qid is a smallint unsigned, not null, auto_increment and is the primary key.
Try this code
<?php
$sql_query = "SELECT snum FROM students";
$result = mysql_query($link,$sql_query);
while ($list = mysql_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = '1' ";
$result = mysql_query($link,$sql_query);
while ($question_list = mysql_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++){
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('".$snum[$i]."' , '');";
$result = mysql_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('".$snum[$i]."','".$qid[$a]."', '', '');";
$result = mysql_query($link,$sql_query);
}
}
?>
This was solved by using mysqli_free_result($result) between the two select queries
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_assoc($result))
{
$snum[] = $list['snum'];
}
mysqli_free_result($result);
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_assoc($result))
{
$qid[] = $list['qid'];
}

Mysql search with semi colon delimited string

I have 2 tables that look like this
table A table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......
What i plan to do is something like this, where i query one table. loop thru the array of results and explode the data with the semicolon delimiter. then loop thru that new array and query it to get the data (note code below not tested)
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
while ($row = mysql_fetch_array($query)) {
$arr = explode(';', $row['features']);
for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}
print_r($r);
is there a way i can achieve this just in mysql, where i match the column in tableB with the ID's in tableA? or maybe by not using a nested loop? performance is key. coz both tables have more than 25k rows of data.
thanks in advance
Check out this code. Reduced few loops.
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);
$str = implode(",", $arr);
$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
What you are looking for is the IN function
This will take an array of id's and give you every result in a single query.
So your code should look like this after you apply it
while ($row = mysql_fetch_array($query)) {
$new_query = str_replace(";", ",", $row['features']);
$sql2 = "SELECT * FROM `tableA` WHERE `id` IN ($new_query)";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}

Categories