Im using a while loop to go through a DB and pull out some questions and answers. That mostly works apart from the facts the the question order isnt correct.
My question is how do I get the questions to print correctly
Eg :
Q1
Q2
A to Q1
Q3
A to Q2
Blank
A to Q3
Heres an image of what I mean:
Here is the code im using minus the query because I know it works. I think its the if statement thats wrong.
$result = mysqli_query($conn, "SELECT
q.QText, q.id AS QId, ua.id, a.AText, ca.id, ca.Answer_ID,
case when a.id = ua.Answer_ID then 'x' else NULL end as IsUserAnswer ,
case when a.id = ca.Answer_ID then 'x' else NULL end as IsCorrectAnswer
FROM user_answers ua
INNER JOIN question q ON q.id = ua.Question_ID
INNER JOIN answer a ON a.Question_ID = q.id
INNER JOIN correct_answer ca ON ca.Question_ID = q.id
WHERE ua.Test_ID=1
ORDER BY q.ID") or die(mysqli_error($conn));
$lastQuestionID = 0;
while ($data2 = mysqli_fetch_array($result))
{
if ($data2['QId'] != $lastQuestionID)
echo '<p>Q. ' . $data2['QText'] . '</p>
<table class="striped centered">
<thead>
<tr>
<th>Answer</th>
<th>Your Answer</th>
<th>Correct Answer</th>
</tr>
</thead>';
$lastQuestionID = $data2['QId'];
echo '
<tr>
<td>' . $data2['AText'] . '</td>
<td>' . $data2['IsUserAnswer'] . '</td>
<td>' . $data2['IsCorrectAnswer'] . '</td>
</tr>';
}
echo "</table>";
Your table closing is defined incorrectly. Do this instead:
$result = mysqli_query($conn, "Query") or die(mysqli_error($conn));
$lastQuestionID = 0;
$isTableOpen = false;
while ($data2 = mysqli_fetch_array($result)) {
if ($data2['QId'] != $lastQuestionID) {
if ($isTableOpen) {
echo '</table>';
}
$isTableOpen = true;
echo '<p>Q. ' . $data2['QText'] . '</p>
<table class="striped centered">
<thead>
<tr>
<th>Answer</th>
<th>Your Answer</th>
<th>Correct Answer</th>
</tr>
</thead>';
}
echo '
<tr>
<td>' . $data2['AText'] . '</td>
<td>' . $data2['IsUserAnswer'] . '</td>
<td>' . $data2['IsCorrectAnswer'] . '</td>
</tr>';
$lastQuestionID = $data2['QId'];
}
if ($isTableOpen) { // Close last open table
echo '</table>';
}
Related
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 2 years ago.
I have a problem with my project and i don't know to where is the bug.
Problem: After i Submit Form data is not fetch in the Page.
I tried var_dump($result) but is not return data.
I will Expose my Code and i hope you can help me or guide me to resolve the problem.
<?php
include "connect.php";
include 'header.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_POST["Search"])) {
$table_name = 'imp_acc';
$query = "
SELECT * FROM '.$table_name.' WHERE available = 'YES'
";
if (isset($_POST["regi"], $_POST["stat"])) {
$query .= "
AND reg " . $_POST["regi"] . " AND stat " . $_POST["stat"] . "
";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
$output .= '
<table class="table">
<thead>
<tr>
<th scope="col">RRG</th>
<th scope="col">LV</th>
<th scope="col">CR</th>
<th scope="col">PR</th>
<th scope="col">FR</th>
<th scope="col">ES</th>
<th scope="col">RO</th>
<th scope="col">BO</th>
<th scope="col">CP</th>
<th scope="col">SK</th>
<th scope="col">LP</th>
<th scope="col">PRI</th>
<th scope="col">Action</th>
<th scope="col"><th>
<th scope="col"></th>
</tr>
</thead>
';
foreach($result as $row)
{
$timestamp = strtotime($row['lap']);
$newformat = date('Y-m-d',$timestamp);
//$product_id = $row["id"];
$output .= '
<tr>
<td>' . $row["regi"] . '</td>
<td>' . $row["lv"] . '</td>
<td>' . $row["crr_rr"] . '</td>
<td>' . $row["prr_rr"] . '</td>
<td>' . $row["frr_rr"] . '</td>
<td>' . $row["stat"] . '</td>
<td>' . $row["b_o"] . '</td>
<td>' . $row["r_o"] . '</td>
<td>' . $row["cc_count"] . '</td>
<td>' . $row["sk_count"] . '</td>
<td>' . $newformat . '</td>
<td>' . $row["pri_cc"] . '</td>
</tr>
';
}
$output .= ' </table>';
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
Also i need your Opinion for finish my Projects.
I have a Search Page with alot of filters options.
Couple of them are not mandatory , are just optional.
Every filter have a different value in form.
I want to continue in this way to makes more POST like this:
if (isset($_POST["regi"], $_POST["stat"] , ....)
Or i can give a chance to Switch statement, to see how it works.
I wait your opinions and ideea.
Thank you for help
I find the error on code.
It was my fault because i using value and not the form name.
In form data i have something like this:
submit: "Search"
and the code need to be like this:
if (isset($_POST["submit"]))
Now i see another problem is my $result because it comes array.
Thank you for your tips and help.
I cant get my pdo prepared statement code to pull the records! Only if I write it in MySQLi code.
filter_month.php with both codes below.
filter_month.php--------PDO-Conversion---Prevent SQL Injection Not working!
<?php
{
include 'db_connection2.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
year(date) = ? AND month(date) = ?
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["year"]],[$_POST["month"]]);
$stmt->fetchAll(PDO::FETCH_ASSOC);
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".001%"><font size=2><span>Attended</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>'; }
$pdo=null;
// By this way you can close connection in PDO.
?>
filter_month.php -----mysqli-----This code works!
<?php
{
include 'db_connection.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
YEAR(date) = '".$_POST["year"]."'
AND
Month(date) = '".$_POST["month"]."'
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$result = mysqli_query($conn, $query);
$conn->close();
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".02%"><font size=2><span>Attended</span></th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
I have tried many different ways to write the code but, cant get to pull records. Just now learning about pdo.
Also trying to add an image of the client side reportmonthpage.php but cant figure out how to post image.
Here is just my filter_year.php, not year and month, and it works. If I remove the brackets as you have suggested it wont pull records any longer.
<?php
{
include 'db_connection2.php';
$query = "SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
YEAR(date) = ?
AND
ar.present = 1
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["year"]]);
$result = $query;
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Total Year Attendance</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>';
}
$pdo=null;
// By this way you can close connection in PDO.
?>
You want an array in the execute function and you've misplace brackets in such a way that you do not have an array.
[$_POST["year"]],[$_POST["month"]] should be [$_POST["year"],$_POST["month"]] to create the array. You have too many brackets.
Here is what I came up with that works! I'm sure it must be wrong, but it works!
<?php
{
include 'db_connection2.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
month(date) = ? AND year(date) = ?
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["month"],$_POST["year"]] );
$result = $query;
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<div align="center"><font size=4>
Total present (by Class)-------PDO------ Not Working Code</font>
</div>
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".001%"><font size=2><span>Attended</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>'; }
$pdo=null;
// By this way you can close connection in PDO.
?>
Thank you all for your time!
I want to show several results of one query, but I need to group some of these results. I think it's better for you to see my problem :
I have this table that shows several trainings :
And when you click on a row, it'll expand and show exercises that correspond to the training's id (here's example values) :
To get all the exercises by training, I made the following query :
SELECT E.id_entrainement, E.intitule_entrainement, E.date_entrainement, EX.id_exercice, EX.reps, EX.poids, M.nom_exm FROM entrainements E, exercices EX, exercices_muscles M WHERE EX.id_entrainement = E.id_entrainement AND EX.membre = E.id_membre AND M.id_exm = EX.id_exercice_muscle AND id_membre='".$user_id."' GROUP BY E.id_entrainement
But when I put in my code the $data['id_entrainement'] for example, it shows me only the first value got by the query as you can see here :
And when I remove the GROUP BY clause from my query, I have this :
I don't know if it's really helpful for you, but here's my php code :
echo '<div class="container">';
echo '<h1>Vos entraînements</h1>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Référence entraînement</th>
<th>Nom de l\'entraînement</th>
<th>Date de réalisation</th>
<th></th>
</tr>
</thead>
<tbody>';
$i=0;
//$getTrainings = $bdd->query("SELECT * FROM entrainements WHERE id_membre='".$user_id."'");
$getTrainings = $bdd->query("SELECT E.id_entrainement, E.intitule_entrainement, E.date_entrainement, EX.id_exercice, EX.reps, EX.poids, M.nom_exm FROM entrainements E, exercices EX, exercices_muscles M WHERE EX.id_entrainement = E.id_entrainement AND EX.membre = E.id_membre AND M.id_exm = EX.id_exercice_muscle AND id_membre='".$user_id."' ");
while ($data = $getTrainings->fetch()) {
$i++;
echo '
<tr class="plusExpand">
<th scope="row">' . $i . '</th>
<td>' . $data['id_entrainement'] . '</td>
<td>' . $data['intitule_entrainement'] . '</td>
<td>' . date("j/n/Y", strtotime($data['date_entrainement'])) . " " . date("G:i", strtotime($data['date_entrainement'])) . '</td>
<td><span class=" glyphicon glyphicon-plus" aria-hidden="true"></span></td>
</tr>
<tr class="exercicesHidden">
<td>1</td>
<td>' . $data['nom_exm'] . '</td>
<td>' . $data['reps'] . '</td>
<td>' . $data['poids'] . '</td>
<td>Up!</td>
</tr>
';
//echo '<tr class="exercicesHidden"><td>Coucou je suis caché!</td></tr>';
}
echo '
</tbody>
</table>
</div>'
I would like all the exercises are stored under one training, and when I click on it, it shows all the exercises from this training.
I hope I gave you all the things to help me to correct this problem!
My idea is to create a Q&A section under a product profile, just like on eBay or Amazon or whatever. The idea is to send a question and then get the owner of the article to reply.
The table has these columns: pid (product ID), id (question ID), question, answer, date (date posted), username.
So if I post a question, I get the ID of the product in which I'm posting and create a question. The the owner just sends the answer to the row that matches the question.
Here's my PHP code to retrieve all the info from that table:
$qanda = '';
$link = mysql_connect("localhost", "youknowwhat", "youknowwhat");
mysql_select_db("youknowwhat", $link);
$qandaq = mysql_query("SELECT * FROM questions WHERE id='$id2' ORDER BY date", $link);
$count = mysql_num_rows($qandaq);
if($count >= 1){
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
}
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
} else {
$qanda = '<div id="answers" align="center">
No questions for this product.
</div>';
}
Now... what you see as a table in the variable $qanda I want to repeat it over and over again but displaying different row data but the concatenation isn't working and I can only get the last row to be displayed. I just can't seem to find out why this isn't working! Am I missing something?
All you have to do is append your divs (.=) while you're inside the while loop that mysql_fetch_array() rows.
Then you'll have a new div for each row your database returns, and you can populate it easily.
$qanda = '';
while($rows = mysql_fetch_array($qandaq)){
$date = $rows['date'];
$q = $rows['question'];
$a = $rows['answer'];
$usrname = $rows['username'];
$qanda .= '<div id="answers" align="center">
<table cellspacing="0" align="center">
<tr align="center">
<td width="200">' . $date . '</td>
<td rowspan="2" width="400"><strong>' . $q . '</strong><br>' . $a . '</td>
<td width="200">Delete</td>
</tr>
<tr align="center">
<td>' . $usrname . '</td>
<td>Report</td>
</tr>
</table>
</div>';
}
I have this query below:
SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, GROUP_CONCAT(DISTINCT Answer ORDER BY Answer SEPARATOR '') AS Answer, q.QuestionMarks
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
JOIN Answer an ON q.QuestionId = an.QuestionId
AND an.SessionId = q.SessionId
WHERE s.SessionName = "GHWSW1" AND q.QuestionId = 1
GROUP BY an.SessionId, an.QuestionId
ORDER BY q.QuestionId, an.Answer
The query above outputs this result below:
SessionId SessionName QuestionId QuestionContent Answer QuestionMarks
1 GHWSW1 1 Here are 2 answers BD 5
So I included the query in the code below and set up a html table:
$assessment = "GHWSW1";
$number = 1;
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent,
GROUP_CONCAT(DISTINCT Answer ORDER BY Answer SEPARATOR '') AS Answer, q.QuestionMarks
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
JOIN Answer an ON q.QuestionId = an.QuestionId AND an.SessionId = q.SessionId
WHERE s.SessionName = ? AND q.QuestionId = ?
GROUP BY an.SessionId, an.QuestionId
ORDER BY q.QuestionId, an.Answer
";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("si", $assessment, $number);
// execute query
$stmt->execute();
// This will hold the search results
$searchQuestionId = array();
$searchQuestionContent = array();
$searchAnswer = array();
$searchMarks = array();
// Fetch the results into an array
// get result and assign variables (prefix with db)
$stmt->bind_result($dbSessionId, $dbSessionName, $dbQuestionId, $dbQuestionContent, $dbAnswer, $dbQuestionMarks);
while ($stmt->fetch()) {
$searchQuestionId[] = $dbQuestionId;
$searchQuestionContent[] = $dbQuestionContent;
$searchAnswer[] = $dbAnswer;
$searchMarks[] = $dbQuestionMarks;
}
?>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<?php
echo "<table border='1' id='markstbl'>
<tr>
<th class='questionth'>Question No.</th>
<th class='questionth'>Question</th>
<th class='answerth'>Answer</th>
<th class='noofmarksth'>Total Marks</th>
</tr>\n";
foreach ($searchQuestionContent as $key=>$question) {
echo '<tr class="questiontd">'.PHP_EOL;
echo '<td class="optiontypetd">'.htmlspecialchars($searchQuestionId[$key]).'</td>' . PHP_EOL;
echo '<td>'.htmlspecialchars($question).'</td>' . PHP_EOL;
echo '<td class="answertd">'.htmlspecialchars($searchAnswer[$key]).'</td>' ;
echo '<td class="noofmarkstd">'.htmlspecialchars($searchMarks[$key]).'</td>' . PHP_EOL;
}
echo "</table>" . PHP_EOL;
?>
So the HTML table displays it like this:
QuestionId QuestionContent Answer QuestionMarks
1 Here are 2 answers BD 5
But I want it like this in the html table:
QuestionId QuestionContent Answer QuestionMarks
1 Here are 2 answers B 5
D
The second Answer D should be in a seperate row and the other rows should have a rowspan. But how can this be achieved?
Session Table:
SessionId (auto) SessionName
1 AAA
Question Table:
SessionId QuestionId (auto) QuestionContent
1 1 What is 2+2?
Answer Table:
AnswerId (auto) SessionId QuestionId Answer
1 1 1 B
2 1 1 D
try this
foreach ($searchQuestionContent as $key=>$question) {
echo '<tr class="questiontd">'.PHP_EOL;
echo '<td class="optiontypetd">'.htmlspecialchars($searchQuestionId[$key]).'</td>' . PHP_EOL;
echo '<td>'.htmlspecialchars($question).'</td>' . PHP_EOL;
echo '<td class="answertd">'.htmlspecialchars($searchAnswer[$key]).'</td>' ;
echo '<td class="noofmarkstd">'.htmlspecialchars($searchMarks[$key]).'</td>' . PHP_EOL;
echo '</tr>';
}
you forget to close the tr tag
Remove the GROUP BY clause and add make the foreach loop look like this:
echo "<table border='1' id='markstbl'>
<tr>
<th class='questionth'>Question No.</th>
<th class='questionth'>Question</th>
<th class='answerth'>Answer</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Total Marks</th>
</tr>\n";
$previous_question_id = null;
foreach ($searchQuestionContent as $key=>$question) {
if ($previous_question_id == $searchQuestionId[$key]) {
$searchQuestionId[$key] = '';
$question = '';
$searchMarks[$key] = '';
}else{
$previous_question_id = $searchQuestionId[$key];
}
echo '<tr class="questiontd">'.PHP_EOL;
echo '<td class="optiontypetd">'.htmlspecialchars($searchQuestionId[$key]).'</td>' . PHP_EOL;
echo '<td>'.htmlspecialchars($question).'</td>' . PHP_EOL;
echo '<td class="answertd">';
echo $searchAnswer[$key];
echo '</td>' ;
echo '<td class="answermarkstd"><input class="individualMarks" name="answerMarks[]" id="individualtext" type="text" "/></td>' . PHP_EOL;
echo '<td class="noofmarkstd">'.htmlspecialchars($searchMarks[$key]).'</td>' . PHP_EOL;
}
echo '</tr>';
echo "</table>" . PHP_EOL;