I am getting a blank dynamic html table - php

I am trying to create dynamic html table but the problem is that it is not displaying any data in the table. I know the query is correct because I tested the query in sql and it outputs the data. The problem I have I am guessing is the dynamic html table itself. Below is the code:
JavaScript/JQuery:
//javascript below will perform calculation between adding numbers between text inputs per each question
//answer for each calculation per question is stored under "Total Marks Remaining" Column
/*If a question only has one answer, then the text input under the "Marks Per Answer" column becomes
read only and displays the same number as the total marks under the "Total Marks Remaining" column
for that question*/
$(function() {
//alert("here");
var questions = $('#markstbl td[class*="_ans"]').length-1;
//disable single entry
for (var i=0;i<=questions;i++){
if($("[class*=q"+i+"_mark]").length ==1){
var t_marks = $("[class*=q"+i+"_ans]").html();
//alert(t_marks);
$("[class*=q"+i+"_mark]").val(t_marks).attr("disabled","disabled");
//$("[class*=q"+i+"_mark]").attr("disabled","disabled");
}
}
//find each question set and add listeners
for (var i=0;i<=questions;i++){
$('input[class*="q'+i+'"]').keyup(function(){
var cl = $(this).attr('class').split(" ")[1]
var questionno = cl.substring(cl.indexOf('q')+1,cl.indexOf('_'));
var tot_marks = $(".q"+questionno+"_ans_org").val();
//alert(tot_marks);
var ans_t=0;
$("[class*=q"+questionno+"_mark]").each(function(){
var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
ans_t+=parseInt(num);
});
ans_t=tot_marks-ans_t;
//alert(ans_t);
//var fixedno = tot_marks;
var ans = (parseInt(ans_t)<0)?tot_marks:ans_t;
$(".q"+questionno+"_ans").val(ans);
$(".q"+questionno+"_ans_text").html(ans);
});
}
});
</script>
PHP:
<?php
if (isset($_POST['id'])) {
$_SESSION['id'] = $_POST['id'];
}
$assessment = $_SESSION['id'];
include('connect.php');
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.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 = ?
ORDER BY q.QuestionId, an.Answer";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s", $assessment);
// 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;
}?>
HTML:
<form id="Marks" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<table border='1' id='markstbl'>
<thead>
<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>
</thead>
<?php
$row_span = array_count_values($searchQuestionId);
$prev_ques = '';
foreach($searchQuestionId as $key=>$questionId){?>
<tbody>
<tr class="questiontd">
<?php
if($questionId != $prev_ques){?>
<td class="questionnumtd" name="numQuestion" rowspan="<?=$row_span[$questionId]?>"><?=$questionId?> <input type="hidden" name="q<?=$questionId?>_ans_org" class="q<?=$questionId?>_ans_org" value="<?=$searchMarks[$key]?>"><input type="hidden" name="q<?=$questionId?>_ans" class="q<?=$questionId?>_ans" value="<?=$searchMarks[$key]?>"></td>
<td class="questioncontenttd" rowspan="<?=$row_span[$questionId]?>"><?=$searchQuestionContent[$key]?> </td>
<?php
}else{?>
<td class="questionnumtd" name="numQuestion" ></td>
<td class="questioncontenttd" ></td>
<?php
}?>
<td class="answertd" name="answers[]"><?=$searchAnswer[$key]?></td>
<td class="answermarkstd">
<input class="individualMarks q<?=$questionId?>_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<?php
if($questionId != $prev_ques){?>
<td class="noofmarkstd q<?=$questionId?>_ans_text" q_group="1" rowspan="<?=$row_span[$questionId]?>"><?=$searchMarks[$key]?></td>
<?php
}else{?>
<td class="noofmarkstd" q_group="1"></td>
<?php
}?>
</tr>
<?php
$prev_ques = $questionId;
}?>
</tbody>
</table>
</form>
Below is the screenshot of what it is displaying:
Below is what the table should display (The Marks per Answer Column contains text inputs for each row)
Below is database design so you can see where the data is coming from:
Session Table: (Where the exam details is stored)
SessionId SessionName
1 AAA
Question Table: (Where questions for each exams are stored)
SessionId QuestionId QuestionContent Total Marks
1 1 Name three features in a ROM 5
1 2 Here is a single answer 5
Answer Table: (Stores answers for each question in each exam)
AnswerId(auto) SessionId QuestionId Answer
1 1 1 A
2 1 1 B
3 1 1 D
4 1 2 True
Individual_Answer Table: (Stores each individual mark for each individual answer)
AnswerId AnswerMarks
1 2
2 2
3 1
4 5
UPDATE:
Looking at my html code, why is it displaying the table like this below:

Check for missing php open tag <?php before include('connect.php');
Also avoid short tags like <?= and replace them with <?php echo

place <tbody> outside the foreach loop
foreach($searchQuestionId as $key=>$questionId){
?>
<tbody>
to
</thead>
<tbody>
....
....
foreach($searchQuestionId as $key=>$questionId){
?>

Unless there is some code that is not being displayed here, perhaps it's as simple as the $assessment variable not being set, so nothing is being sent to the query?
Also, to confirm that you are actually getting the results back AND binding them OK, I'd be doing a var_dump on the arrays like searchQuestionContent to make sure they have the content you expect in them, if not you know your problem is in the query / binding data. If they do have the content you expect, then you know the problem lies in the table output.

Related

Undefined result with a PDO query with several inner join, but correct query in SQL

I am blocked since 2 days about this problem.
I want to display an info from other table in my "info_array".
http://www.noelshack.com/2022-32-4-1660224518-type-miss.png
Td's "Type d'alarme" has the missing info, which calls another table. But i can't explain why.
All info for client call the table client, "Type d'alarme" calls type_alarme's table. There is no column connexion between them. That's why I use "inner join" in my PDO query.
I searched different method to join the result of the 2 tables but no success.
Here my HTML code for this part (it concerns "td id="alarme_type_client"></td") :
<table id="info_client" border=1>
<thead>
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Date de naissance</th>
<th>Adresse</th>
<th>Adresse mail</th>
<th>Téléphone</th>
<th>Age</th>
<th>Type d'alarme</th>
</tr>
</thead>
<tbody>
<tr id=<?php echo $client["id_client"]; ?>>
<td id="id"></td>
<td id="nom"></td>
<td id="prenom"></td>
<td id="date" name="date"></td>
<td id="adresse"></td>
<td id="mail"></td>
<td id="tph"></td>
<td id="age"></td>
<td id="alarme_type_client"></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="hide_client">Masquer client</button></td>
</td>
</tr>
</tbody>
</table>
My ajax function :
$(".info").click(function () {
var datas = {
cmd: 'id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
}).done(function (sendinfo) {
$('#alarme_type_client').html(sendinfo.nom_type_alarme),
console.log(sendinfo.nom_type_alarme);
});
});
My PHP function :
function read_type(){
global $db;
$id_client = $_GET['id_client'];
$sql = "SELECT nom_type_alarme FROM type_alarme
INNER JOIN alarme on type_alarme.id_type_alarme = alarme.id_type_alarme
INNER JOIN client ON alarme.id_client=client.id_client
WHERE id_client = :id_client";
$query = $db->prepare($sql);
$query->bindParam(':id_client', $id_client, PDO::PARAM_STR);
$query->execute();
$sendinfo = $query->fetch();
print_r($sendinfo);
return ($sendinfo);
}
http://www.noelshack.com/2022-32-4-1660225072-resultat-sql.png
In Heidi SQL (Laragon), the query works. I use the 2 inner join 'cause alarme is my principal table which union the info what I need
It displays the info client if I erase the " type_alarme.nom_type_alarme" at the beginning of query.
Any ideas ? I don't find solution.
Thanks for help.
It is because you are not joining the type_alarme table at all. Why? Because in your SQL query you have a semicolon ; just before you do INNER JOIN type_alarme. So the query is interrupted there and hence the type_alarme.nom_type_alarme in the SELECT clause doesn't know which table and column is that.
Remove the semicolon and it will work.

Dynamic row span php while loop

i have two tables one item table and customer table:
in the table you can see the second item item id 1002 have two entries.and i want to add colspan to that item for column 1 and 3.
<table>
<tr>
<th>Item ID</th>
<th>Item Color</th>
<th>Customer</th>
</tr>
<?php
$sql = mysqi_query($con,"select * from item_table");
while($row = mysqli_fetch_array($sql)){
?>
<tr>
<td><?=$row['item_id'];?></td>
<td><?=$row['item_color'];?></td>
<td>
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
But it print in normal way, i have no idea how to add rowspan in loop..please suggest some logic to solve its appreciated.
You can try it this way:
First, add a counter to your query that will indicate how many entries has a given item.
$sql_cust = mysqli_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as c
FROM item_table");
Then, when looping through the items you will set the rowspan to the number of entries the item has. Below is the whole code adjusted.
<?php
$sql = mysqi_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as entry_count
FROM item_table");
$buffer = [];
while($row = mysqli_fetch_array($sql)){
if(!isset($buffer[$row[$item_id]])) {
$buffer[$row[$item_id]] = 1;
}
?>
<tr>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>"><?=$row['item_id'];?></td>
<?php }?>
<td><?=$row['item_color'];?></td>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>">
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
<?php }?>
</tr>
<?php
}
?>
Note that I added a buffer where I set which item was already displayed. That array is used so you only open one td with the wanted rowspan, instead of doing it on every iteration.
i have a simple idea
give TD a ID like
<td id="dynamically-Generate"> (you need to verify that TD id need to be equal in .rowSpan ="here" inside script )
and set this TD if dynamically-Generate is greater than 1 then don't show
and again if dynamically-Generate is greater than 1 then then use this script
<script>
document.getElementById("dynamically-Generate").rowSpan = "dynamically-Generate";
</script>
use script inside loop and both dynamically-Generate need to be same inside everyloop and change after each loop

How do I return only select rows that meet user search condition

I have a webpage (i am beginner php for only 1.5 months following book examples) that allows a user to enter a gpa and then search for students that meet the minimum entered. When the search button is clicked it calls a function from php file to query the database. My code is almost working right. The problem is it is returning all students and I want to return only the rows that meet minimum gpa entered. Tried to use HAVING clause and others but still doesn't return what I want. Thanks!
Link to sql fiddle: http://www.sqlfiddle.com/#!2/be9da
html:
<script type="text/javascript">
function queryStudent() {
var ajaxRequest = new XMLHttpRequest;
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
document.getElementById("ajax_output").innerHTML = ajaxRequest.responseText;
}
};
ajaxRequest.open("GET", "gpa_search.php", true);
ajaxRequest.send(null);
}
</script>
<form name="student">
<label>Minimum GPA: </label>
<input type="text" id="GPA" name="gpa"><br><br>
<input type="button" onclick="queryStudent();" value="Search" id="button">
</form><br>
<!--output section after search-->
<section id="ajax_output">
</section><br><br>
<p>Students with higher than minimum GPA will be displayed here.</p><br>
Search & Split
php:
<?php
//get user input from text box on index.htm
$GPA = filter_input(INPUT_GET, 'GPA');
//Code for query
$query = 'SELECT *
FROM student
ORDER BY studentID';
$statement = $db->prepare($query);
$statement->bindValue(':GPA', "%".$GPA."%", PDO::PARAM_STR);
$statement->execute();
$students = $statement->fetchAll();
?>
<!--table to hold output-->
<table>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Email</th>
<th>GPA</th>
</tr>
<?php foreach ($students as $student) : ?>
<tr>
<td><?php echo $student['studentID']; ?></td>
<td><?php echo $student['name']; ?></td>
<td><?php echo $student['email']; ?></td>
<td><?php echo $student['GPA']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<body>
</body>
</html>
On your code use the following:
$query = 'SELECT *
FROM student
WHERE GPA >= :GPA
ORDER BY studentID';
$statement->bindValue(':GPA', $GPA, PDO::PARAM_STR);
This will search for students that have GPA greater and equal to $GPA, If you want to retrieve students that have only that GPA specifically then change WHERE GPA = :GPA
Check your SQL query, the error is most likely from there. Your select statement doesn't have a where clause. It should be something like select * from students where GPA = :GPA Order by studentid

How to calculate the difference in example below

I want to calculate difference between the "Total Marks" in a question, and the text inputs for each answer in a question. Also if a question has only one answer, then it should display the text input as a readonly and display the same value as the number under the "Total Mark" for that question in that text input.
Below is a screenshot which shows the table and the written problem I have with both scenarios:
Below is the current jquery variable which should be doing the calculation and display the readonly textbox when necessary. But at the moment it is not working. Also at the moment I have display the number for total marks to be fixed as "5" when doing the calculations, well this is incorrect as that it should be the number for within each row, so I believe the variable $sessionMarks that should be the number, not 5.
$(function(){
var questions = $('#markstbl td[class*="_ans"]').length-1;
//disable single entry
for (var i=0;i<=questions;i++){
if($("[class*=q"+i+"_mark]").length ==1){
$("[class*=q"+i+"_mark]").attr("disabled","disabled")
}
}
//find each question set and add listeners
for (var i=0;i<=questions;i++){
$('input[class*="q'+i+'"]').keyup(function(){
var cl = $(this).attr('class').split(" ")[1]
var questionno = cl.substring(cl.indexOf('q')+1,cl.indexOf('_'))
var t=0;
$("[class*=q"+questionno+"_mark]").each(function(){
var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
t+=parseInt(num);
})
var fixedno = 5;
$(".q"+questionno+"_ans").text((t>fixedno)?fixedno:t);
})
}
})
Below is the code for the table, from the query it outputs the details of each question from the database and then it displays it in a table:
<?php
$assessment = $_SESSION['id'] . $sessionConcat;
include('connect.php');
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.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 = ?
ORDER BY q.QuestionId, an.Answer
";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s", $assessment);
// 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;
}
?>
....
<tbody>
<tr>
<?php
$previous_question_id = null;
$rowspans = array_count_values($searchQuestionId);
$output = "";
$questionid = 0; //whole question
$questionno = 0; //part of question
foreach ($searchQuestionContent as $key => $question) {
if ($previous_question_id != $searchQuestionId[$key]){
$questionno=0;
}
// removed logic, not necessary to set empty strings if you're skipping them
$output.= '<tr class="questiontd">' . PHP_EOL;
if ($previous_question_id != $searchQuestionId[$key]) {
$output.= '<td class="questionnumtd" name="numQuestion" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($searchQuestionId[$key]) . '</td>' . PHP_EOL;
$output.= '<td class="questioncontenttd q{$questionno++}_mark{$questionid}" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($question) . '</td>' . PHP_EOL;
}
$output.= '<td class="answertd" name="answers[]">';
$output.= $searchAnswer[$key];
$output.= '</td>';
$output.= '<td class="answermarkstd"><input class="individualMarks" q_group="1" name="answerMarks[]" id="individualtext" type="text" /></td>' . PHP_EOL;
if ($previous_question_id != $searchQuestionId[$key]) {
$output.= '<td class="noofmarkstd q{$questionid++}_ans" q_group="1" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($searchMarks[$key]) . '</td>' . PHP_EOL;
}
// moved this to the end
if ($previous_question_id != $searchQuestionId[$key]) {
$previous_question_id = $searchQuestionId[$key];
}
}
echo $output;
?>
</tr>
</tbody>
Update:
In the sample HTML which is in this fiddle, I can get it to work (except I want the calculation to be total marks minus number entered in text input, not what it is doing now which is when I enter a number in text input it performs an addition from 0 to whatever number entered in text input), but when I tried to edit the code above to do the same thing, then it doesn't work, nothing happens.
The sample html is below:
<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">
<table border='1' id='markstbl'>
<thead>
<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>
</thead>
<tbody>
<tr class="questiontd">
<td class="questionnumtd" name="numQuestion" rowspan="3">1</td>
<td class="questioncontenttd" rowspan="3">Name three features in a ROM</td>
<td class="answertd" name="answers[]">A</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="noofmarkstd q0_ans" q_group="1" rowspan="3">5</td>
</tr>
<tr class="questiontd">
<td class="answertd" name="answers[]">B</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_1" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
</tr>
<tr class="questiontd">
<td class="answertd" name="answers[]">D</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_2" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
</tr>
<tr class="questiontd">
<td class="questionnumtd" name="numQuestion" rowspan="1">2</td>
<td class="questioncontenttd" rowspan="1">Here is a single answer</td>
<td class="answertd" name="answers[]">True</td>
<td class="answermarkstd">
<input class="individualMarks q1_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="noofmarkstd q1_ans" q_group="1" rowspan="1">5</td>
</tr>
</tbody>
</table>
</form>
Below is what the database tables looks like, (this will follow the same data as the ones in the screenshot)
Session Table: (Where the exam details is stored)
SessionId SessionName
1 AAA
Question Table: (Where questions for each exams are stored)
SessionId QuestionId QuestionContent Total Marks
1 1 Name three features in a ROM 5
1 2 Here is a single answer 5
Answer Table: (Stores answers for each question in each exam)
AnswerId(auto) SessionId QuestionId Answer
1 1 1 A
2 1 1 B
3 1 1 D
4 1 2 True
Individual_Answer Table: (Stores each individual mark for each individual answer)
AnswerId AnswerMarks
1 2
2 2
3 1
4 5
It is not good practice to get and put values from html elements using html() which somehow belong to calculation or integers values, Therefore always use hidden fields for this type of problems, like I have included two hidden fields one for original value and one for the final value and at the end you can get the total marks values easily from the hidden field.
The code is updated for dynamic data. Use your own code for queries, mine is a rough code.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
var questions = $('#markstbl td[class*="_ans"]').length;
//disable single entry
for (var i=1;i<=questions;i++){
if($("[class*=q"+i+"_marks]").length ==1){
var t_marks = $("[class*=q"+i+"_ans]").html();
alert(t_marks);
$("[class*=q"+i+"_marks]").val(t_marks).attr("disabled","disabled");
//$("[class*=q"+i+"_mark]").attr("disabled","disabled");
}
}
//find each question set and add listeners
for (var i=0;i<=questions;i++){
$('input[class*="q'+i+'"]').keyup(function(){
var cl = $(this).attr('class').split(" ")[1]
var questionno = cl.substring(cl.indexOf('q')+1,cl.indexOf('_'));
var tot_marks = $(".q"+questionno+"_ans_org").val();
var ans_t=0;
$("[class*=q"+questionno+"_marks]").each(function(){
var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
ans_t+=parseInt(num);
});
ans_t=tot_marks-ans_t;
var ans = (parseInt(ans_t)<0)?tot_marks:ans_t;
$(".q"+questionno+"_ans").val(ans);
$(".q"+questionno+"_ans_text").html(ans);
});
}
});
</script>
</head>
<body>
<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">
<?php
$ident = mysqli_connect('localhost','root','');
mysqli_select_db($ident,'testdata');
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.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
ORDER BY q.QuestionId, an.Answer
";
$res = mysqli_query($ident,$query);
$searchQuestionId = array();
$searchQuestionContent = array();
$searchAnswer = array();
$searchMarks = array();
while ($row = mysqli_fetch_array($res)) {
$searchQuestionId[] = $row['QuestionId'];
$searchQuestionContent[] = $row['QuestionContent'];
$searchAnswer[] = $row['Answer'];
$searchMarks[] = $row['QuestionMarks'];
}
?>
<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">
<table border='1' id='markstbl'>
<thead>
<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>
</thead>
<tbody>
<?php
$row_span = array_count_values($searchQuestionId);
$output = '';
$rowCount = 1;
$newQuest_id = true;
foreach($searchQuestionId as $key=>$questionId){
if($newQuest_id == true){
$output.= '<tr class="questiontd">';
$output.= '<td class="questionnumtd" name="numQuestion" rowspan="'.$row_span[$questionId].'">'.$questionId.' <input type="hidden" name="q'.$questionId.'_ans_org" class="q'.$questionId.'_ans_org" value="'.$searchMarks[$key].'"><input type="hidden" name="q'.$questionId.'_ans" class="q'.$questionId.'_ans" value="'.$searchMarks[$key].'"></td>';
$output.= '<td class="questioncontenttd" rowspan="'.$row_span[$questionId].'">'.$searchQuestionContent[$key].' </td>';
}
$output.= '<td class="answertd" name="answers[]">'.$searchAnswer[$key].'</td>';
$output.= '<td class="answermarkstd">';
$output.= '<input class="individualMarks q'.$questionId.'_marks" q_group="1" name="answerMarks[]" id="individualtext" type="text" />';
$output.= '</td>';
if($newQuest_id == true){
$output.= '<td class="noofmarkstd q'.$questionId.'_ans_text" q_group="1" rowspan="'.$row_span[$questionId].'">'.$searchMarks[$key].'</td>';
$newQuest_id = false;
}
$output.= '</tr>';
if($row_span[$questionId] == $rowCount){
$newQuest_id = true;
}
$rowCount++;
}
echo $output;
?>
</tbody>
</table>
</form>
</form>
</body>
</html>

How to merge fields together and display output in php and sql

I don't know how to explain this but what I want to do is kind of merge two database field together and output the new field using php. For example:
Answer Table:
AnswerId: 10
AnswerContent: Manchester
AnswerId :11
AnswerContent: Leeds
AnswerId:12
AnswerContent:Birmingham
StudentAnswer Table:
Student: Bob
StudentAnswer:10
Student: Jim
StudentAnswer:11
What I want to do is that when I run the query which I will show below with my php coding, for the StudentAnswer field I want it to display the name of the answer rather than the answer id. How can this be achieved?
Below is the code:
<?php
if (isset($_POST['submit'])) {
$query = "
SELECT * FROM Question q
INNER JOIN StudentAnswer sa ON q.QuestionId = sa.QuestionId
JOIN Answer a ON sa.QuestionId = a.QuestionId
WHERE
('".mysql_real_escape_string($sessionid)."' = '' OR q.SessionId = '".mysql_real_escape_string($sessionid)."')
AND
('".mysql_real_escape_string($questionno)."' = '' OR q.QuestionNo = '".mysql_real_escape_string($questionno)."')
AND
('".mysql_real_escape_string($studentid)."' = '' OR sa.StudentId = '".mysql_real_escape_string($studentid)."')
AND(CorrectAnswer = '1')
ORDER BY $orderfield ASC";
$num = mysql_num_rows($result = mysql_query($query));
mysql_close();
?>
<p>
Your Search:
<strong>Session ID:</strong> <?php echo (empty($sessionid)) ? "'All Sessions'" : "'$sessionid'"; ?>,
<strong>Question Number:</strong> <?php echo (empty($questionno)) ? "'All Questions'" : "'$questionno'"; ?>,
<strong>Student Username:</strong> <?php echo (empty($studentid)) ? "'All Students'" : "'$studentid'"; ?>,
<strong>Order Results By:</strong> '<?php echo $ordername; ?>'
</p>
<p>Number of Records Shown in Result of the Search: <strong><?php echo $num ?></strong></p>
<table border='1'>
<tr>
<th>Session ID</th>
<th>Question Number</th>
<th>Question</th>
<th>Correct Answer</th>
<th>StudentAnswer</th>
<th>Correct Answer Weight</th>
<th>Student Answer Weight</th>
<th>Student ID</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['QuestionNo']}</td>
<td>{$row['QuestionContent']}</td>
<td>{$row['AnswerContent']}</td>
<td>{$row['StudentAnswer']}</td>
<td>{$row['Weight%']}</td>
<td></td>
<td>{$row['StudentId']}</td>
</tr>";
}
?>
</table>
<?php
}
?>
Thank You
I think you could use:
SELECT q.*, a.AnswerContent FROM Question q
INNER JOIN StudentAnswer sa ON q.QuestionId = sa.QuestionId
INNER JOIN Answer a ON sa.QuestionId = a.QuestionId
WHERE ....
I mean, you should return the text for the answer (you're still joining tables, so you do have that field).

Categories