Multiple Choice Quiz - not updating responses - php

I have a form that outputs:
Quiz_Assign_ID (Combines User_ID with Quiz ID)
Question ID
Checkboxes for inputting the response (Option A, Option B, Option C)
<div class="Main">
<form method="post" action="LP_Quiz_Student_Quiz_Responses.php">
<?php
$quiz_id = trim($_GET['quiz_id']);
$quiz_assign_id = trim($_GET['quiz_assign_id']);
$i = 1;
$count=1;
$sel_query=("SELECT Quiz.quiz_id, Quiz.quiz_title, Quiz_Questions.quiz_id, Quiz_Questions.quiz_question_id, Quiz_Questions.question, Quiz_Questions.option1, Quiz_Questions.option2, Quiz_Questions.option3, Quiz_Questions.answer FROM Quiz, Quiz_Questions WHERE (Quiz.quiz_id=Quiz_Questions.quiz_id) and (Quiz.quiz_id=?)");
$stmt = $conn->prepare($sel_query);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows === 0) exit('No Quiz Questions!');
while($row = $result->fetch_assoc()) { ?>
<p></p>
<p> </p>
<table>
<tr>
<td>
</td>
<td>
<input name="quiz_assign_id" type="hidden" value=" <?php echo $quiz_assign_id; ?>" /> <input name="quiz_question_id" type="hidden" value=" <?php echo $row["quiz_question_id"]; ?>" /></td>
<td> </td>
</tr>
<tr>
<td>
<h4>Question <?php echo $i++; ?> </h4>
</td>
<td>
<h4><?php echo $row["question"]; ?> </h4>
</td>
<td> </td>
</tr>
<tr>
<td>
<h4>A</h4>
</td>
<td><?php echo $row["option1"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option A" style="width: 20px" /></td>
</tr>
<tr>
<td>
<h4>B</h4>
</td>
<td><?php echo $row["option2"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option B" /></td>
</tr>
<tr>
<td>
<h4>C</h4>
</td>
<td><?php echo $row["option3"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option C" /></td>
</tr>
</table>
<?php
}
?>
<input name="Submit1" type="submit" value="submit" />
</form>
</div>
Upon submission I run the following script, which captures the response but does not get the question_id and Quiz_Assign_ID and does not update the values in the database:
<?php
if(!empty($_POST['Response'])) {
foreach ($_POST['Response'] as $value) {
$quiz_assign_id=trim($_POST['quiz_assign_id']);
$quiz_question_id=$_POST['quiz_question_id'];
echo 'Answer'; echo $value;
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
$stmt = $conn -> prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
if (
$stmt &&
$stmt -> bind_param('sss', $value, $quiz_assign_id, $quiz_question_id) &&
$stmt -> execute() &&
$stmt -> affected_rows === 1
) {
echo "<script>
alert('Responses submitted!');
window.history.go(-2);
</script>";
} else {
echo"<script>
window.history.go(-2);
</script>";
}
}
}
?>
I have been playing with it for hours, but with no luck.

Because you are using check boxes en not radio buttons, you should change your input checkbox name attribute, so it's sending a nested array with the question ID as a key and the answers array as the value, like so: (notice the extra []) Also $quiz_question_id is not defined, you should use the $row array.
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
Because the response array is now nested, the question answers are grouped by question_id. To iterate over the nested response array, use the following for loop:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
}
So your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
echo 'Answers'; print_r($values); // Values is an array here.
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
// Because $values is an array, transform it into a comma separated string to insert them into the database
// But you could also make a database table with answers and loop over the $values array.
$value = implode(', ', $values);
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $value, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
To accommodate both type of questions with check boxes and questions with radio buttons, you can use the same response code, but first check if its an array before transforming it into a string.
Questions with radio buttons, one answer per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>]" type="radio" value="Option A" style="width: 20px" /></td>
Questions with check boxes, multiple answers per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
And now your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
// If it's an array (checkbox), transform to string.
// Else it is already a string (radio).
if (is_array($values)) {
$values = implode(', ', $values);
}
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $values, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('".$done." Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
But with above code you can accommodate all kind of field types.
To put it simple:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// Check if array, it's a checkbox or multiple select question
if (is_array($answered)) {
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
} else {
// radio, hidden, input, select or textarea question
echo "Answered: ".$answered."<br />";
}
}
I hope this points you in the right direction.

Related

Increment score only when the user's answer is correct

Im a student and new to php. Im currently working on a skill test project where scores in different categories (which are ABM, HUMSS, STEM, GAS, TVL) are counted. The problem is the scores still increment even when the user's answer is wrong. I hope someone can help me fix my codes..
results.php
if(isset($_POST['submit'])) {
$ans = $_POST['ans'];
$abmscore = 0;
$humssscore = 0;
$stemscore = 0;
$gasscore = 0;
$tvlscore = 0;
if( !empty($ans)):
foreach($ans as $qID => $qVal) {
$qID = (int) $qID;
$qVal = (int) $qVal;
$query1= "SELECT COUNT(*) AS rightAnswer FROM tquestions WHERE test_id = $qID AND correctanswer = $qVal";
$result1= mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$query2 = "SELECT strand FROM tquestions WHERE test_id = $qID";
$result2 = mysqli_query($conn, $query2);
$row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC);
$strand = $row2['strand'];
if (!$result2) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if($row1['rightAnswer']) {
if($strand == 'ABM' ) {
$abmscore++;
}
elseif ($strand == 'HUMSS' ) {
$humssscore++;
}
elseif ($strand == 'STEM' ) {
$stemscore++;
}
elseif ($strand == 'GAS' ) {
$gasscore++;
}
elseif ($strand == 'TVL' ) {
$tvlscore++;
}
}
}
endif;
}
test.php
$sql = "SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 0, 50";
$result = mysqli_query ($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
<form action="results.php" method="POST">
<?php if (mysqli_num_rows($result) > 0): ?>
<?php $index = 1; $num = 1; ?>
<?php foreach ($result as $results):
$question = $results['question'];
$optiona = $results['optiona'];
$optionb = $results['optionb'];
$optionc = $results['optionc'];
$optiond = $results['optiond'];
$test_id = $results['test_id'];
?>
<div id="q<?php echo ($index++); ?>" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $num,'. ', $question; ?> </h3>
</tr>
<tr class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
</tbody>
</table>
</div>
<?php $num++; ?>
<?php endforeach ?>
<?php endif ?>
<br>
<div class="form-group"><center>
<input class="btn btn-success" type="submit" name="submit" value="Submit" onclick="return confirm('Are you sure you want to submit your answers?')"></center>
</div>
Here is my database table of test questions:
There is a lot packed in here and I have tested it to be successful, but if anyone finds a flaw, let me know and I'll fix it up.
This is the database table data that I am working with: http://sqlfiddle.com/#!9/036c06/1/0
This is my test.php code:
if (!$conn=new mysqli($host,$user,$pass,$db)) {
echo "Database Connection Error: " , $conn->connect_error; // don't show error messages to the public
} elseif (!$result = $conn->query('SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 50')) {
echo "Syntax Error: " , $conn->error; // don't show error messages to the public
} elseif (!$result->num_rows) {
echo "Logic Error: No Rows # Questions Query";
} else {
echo "<form action=\"results.php\" method=\"POST\">";
$i = 0;
while ($row=$result->fetch_assoc()) {
echo "<div id=\"q",++$index,"\" class=\"tabcontent\">";
echo "<table class=\"table table-hover\">";
echo "<tbody>";
echo "<tr class=\"form-group\">";
echo "<h3 name=\"ques{$row['test_id']}\" style=\"text-indent:40px;\"> " , ++$i , ". {$row['question']} </h3>"; // can't see a reason to have a name attribute here
echo "</tr>";
$options = [$row['optiona'],$row['optionb'],$row['optionc'],$row['optiond']];
shuffle($options); // shuffle the options to improve test structure
echo "<tr class=\"form-group\">";
foreach ($options as $option) {
echo "<label class=\"radio-inline\" style=\"text-indent:70px;font-size:18px;\"> ";
echo "<input style=\"font-size:18px;\" type=\"radio\" name=\"ans[{$row['test_id']}]\" value=\"$option\">$option";
echo "</label><br>";
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
echo "</div>";
}
echo "<div class=\"form-group\">";
echo "<center><input class=\"btn btn-success\" type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"return confirm('Are you sure you want to submit your answers?')\"></center>";
echo "</div>";
echo "</form>";
}
Some notes:
I don't like to bounce in and out of php, so I just stay inside php and echo everything out (personal preference).
I have elected to use object-oriented mysqli syntax (personal preference).
I have removed the name attribute on the <h3> tag because I don't see the benefit. If you have a reason, just re-add it.
I have shuffled the options for each question so that the test seems "fresh" each time.
I have displayed the options in a loop to make the code more DRY.
This is my results.php code:
if (!isset($_POST['submit']) && !empty($_POST['ans'])) {
echo "Insufficient Submission Data Received";
} elseif (!$conn=new mysqli($host,$user,$pass,$db)) {
echo "Database Connection Error: ",$conn->connect_error;
} else {
$params = array_keys($_POST['ans']); // collect test_ids from submission data
$results = array('ABM'=>0,'HUMSS'=>0,'STEM'=>0,'GAS'=>0,'TVL'=>0); // init / zero-out the categories
$count = count($params); // number of fullstring matches
$csph = implode(',',array_fill(0,$count,'?')); // comma-separated placeholders
if (!$stmt=$conn->prepare("SELECT test_id,strand,correctanswer FROM tquestions WHERE test_id IN ($csph);")) {
echo "Syntax Error # prepare: " , $conn->error; // don't show error messages to the public
} else {
array_unshift($params, str_repeat('s', $count)); // prepend the type values string
$ref = []; // add references
foreach ($params as $i=>$v) {
$ref[$i] = &$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt, 'bind_param'], $ref);
if (!$stmt->execute()) {
echo "Error # bind_param/execute: ",$conn->error;
} elseif (!$stmt->bind_result($test_id,$strand,$correctanswer)) {
echo "Error # bind_result: " , $stmt->error; // don't show error messages to the public
} else {
while ($stmt->fetch()) {
if (isset($_POST['ans'][$test_id], $results[$strand]) && $_POST['ans'][$test_id] == $correctanswer) {
++$results[$strand];
}
}
$stmt->close();
var_export($results);
}
}
}
Some notes:
I am only doing some basic submission checking at the start of the script. you can make additional refinements if you are so inclined.
As a matter of database protection, I use a prepared statement to query the database with user-provided data. Unfortunately, the process of generating a "safe" IN clause is rather verbose. You don't need to "understand" all of the components involved with call_user_func_array() if you are just beginning your journey with php. You may just trust it for now, and research it later when you want to wrap your head around it.
I decided to store the categorical correct answer tally as an array of data, rather than individual variables since it is a set of data with the same uniform structure.
If you wonder about the data assigned to particular values in my scripts, just write some strategically placed echos or var_export()s on the variables.
When I submit a "perfect" form to result.php, this is the $_POST data:
array ( 1 => '1 and 0', 8 => 'Marcelo del Pilar', 7 => 'Marcelo del Pilar', 3 => 'Liability', 5 => 'Variable', 4 => 'Crisis', 6 => 'Marcelo del Pilar', )
and this is the $results data:
array ( 'ABM' => 1, 'HUMSS' => 1, 'STEM' => 1, 'GAS' => 3, 'TVL' => 1, )
edited:
Okay, this may need some explanation afterward, but I believe I've found a solution for you. Your code, as you have it now, gives all of your radio options the same name: ans<?php echo $test_id ?>. By doing this, you're passing all 4 options at once to the same variable. That's an issue.
Change the names of your inputs to be unique, and also pass test_id to results.php in a hidden input:
<tr class="form-group">
<input type="hidden" name="test_id" value="<?php echo $test_id ?>">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_a" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_b" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_c" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_d" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
Then update your test.php like to check WHICH radio was selected and grab the test_id from that hidden field:
if(isset($_POST['submit'])) {
if (isset($_POST['option_a'])) $ans = $_POST['option_a'];
if (isset($_POST['option_b'])) $ans = $_POST['option_b'];
if (isset($_POST['option_c'])) $ans = $_POST['option_c'];
if (isset($_POST['option_d'])) $ans = $_POST['option_d'];
if (isset($_POST['test_id'])) $id = $_POST['test_id'];
Then remove your foreach loop and fix your SQL query to "SELECT correctanswer FROM tquestions WHERE test_id = $id", because we have all of the other info, we only need the correct answer based on the ID of the question we passed from test.php
$query1= "SELECT correctanswer AS rightAnswer FROM tquestions WHERE test_id = $id";
In the end, results.php should look like this:
if(isset($_POST['submit'])) {
if (isset($_POST['option_a']) $ans = $_POST['option_a'];
if (isset($_POST['option_b']) $ans = $_POST['option_b'];
if (isset($_POST['option_c']) $ans = $_POST['option_c'];
if (isset($_POST['option_d']) $ans = $_POST['option_d'];
if (isset($_POST['test_id'])) $id = $_POST['test_id'];
$abmscore = 0;
$humssscore = 0;
$stemscore = 0;
$gasscore = 0;
$tvlscore = 0;
$query1= "SELECT correctanswer AS rightAnswer FROM tquestions WHERE test_id = $id";
$result1= mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$query2 = "SELECT strand FROM tquestions WHERE test_id = $id";
$result2 = mysqli_query($conn, $query2);
$row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC);
$strand = $row2['strand'];
if (!$result2) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if($ans == $row1['rightAnswer']) {
if($strand == 'ABM') {
$abmscore++;
}
elseif ($strand == 'HUMSS') {
$humssscore++;
}
elseif ($strand == 'STEM') {
$stemscore++;
}
elseif ($strand == 'GAS') {
$gasscore++;
}
elseif ($strand == 'TVL') {
$tvlscore++;
}
}
}
Your test.php had some unnecessary things in it. You don't need to use for every line of PHP code. You only need to open it and close it between parsing other languages like HTML. If you'd like me to explain further I'd be happy, but for now, I've tweaked test.php:
$sql = "SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 0, 50";
$result = mysqli_query ($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
<form action="results.php" method="POST">
<?php if (!mysqli_num_rows($result) > 0) die('No data');
foreach ($result as $results) {
$question = $results['question'];
$optiona = $results['optiona'];
$optionb = $results['optionb'];
$optionc = $results['optionc'];
$optiond = $results['optiond'];
$test_id = $results['test_id'];
} ?>
<div id="q<?php echo ($index++); ?>" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $num,'. ', $question; ?> </h3>
</tr>
<tr class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
</tbody>
</table>
</div>
<br>
<div class="form-group"><center>
<input class="btn btn-success" type="submit" name="submit" value="Submit" onclick="return confirm('Are you sure you want to submit your answers?')"></center>
</div>
For my sake, I hope this works out for you.

PHP/MySQL: Show only specific columns within a loop?

I am programming a voting system where users can upload up to 20 images per project (see attached image). Currently I am displaying per Row the project ID, an image and a text (text is the same in the same project). When the user adds 20 Images to the project the text will be shown 20 times. Now I am trying to rebuild the display part (see the attached Image) - instead of 20 rows, there should only be one row per user and project, but I have no clue how to achieve this. Thank you for your help.
This is my SQL syntax:
SELECT * from wp_awa_upload WHERE wp_awa_upload.uid = '$_SESSION[id]' and stat < 3 order by parent_cat, id asc
And this is the Part where I print the result of the table:
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
<? $i = 0; ?>
<? while ($show = mysql_fetch_array($abfrage)) { ?>
<form action="" method="POST">
<td><? echo $show['parent_cat'];?><br><input name="uid" type="#hidden" class="style13" value="<?php echo $show['uid']; ?>" id="uid" style="width: 40px" readonly /></td>
<td align="center"><? echo $show['file_name']; ?><br><div class="center-cropped"><img src="<? echo $show['url'] ?>" border="0"><br></div><br>©: <input name="copyright" type="text" class="style13" value="<?php if ($rolle <> '1') {echo $show['copyright'];} ?>" id="copyright" style="width: 140px" /><br><? if ( $show['youtube'] <> '') { echo 'Youtube'; }?></td>
<td><textarea name ='project' rows='16' cols='30' style="resize: none;"><?php if ($i == 0) { echo $show['project']; } ?></textarea></td>
<td><textarea name ='testimonial' rows='16' cols='30' style="resize: none;"><?php echo $show['testimonial']; ?></textarea><br>
<? if ($show['parent_cat'] == "Bester Styled Shoot") { ?>Styled Shoot Teilnehmer<br>
<textarea name ='styled' rows='8' cols='30' style="resize: none;"><?php echo $show['styled']; } ?></textarea></td>
<td><textarea name ='beschreibung' rows='16' cols='30' style="resize: none;"><?php echo $show['beschreibung']; ?></textarea></td>
<td><? if ($rolle <> 1 && $show['stat'] == 0 ) { echo '<button type="submit" value="' . $show['id']. '" name="change">Speichern?</button>'; ?><br><? echo '<button type="submit" value="' . $show['id']. '" name="delete">Löschen?</button>'; } ?></td>
<td><? if ($rolle == '1') { ?>
<select name="rating" class="style28" style="width: 120px" id="rating">
<option value="0">0</option>
<option value="5">5</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
<option value="70">70</option>
<option value="75">75</option>
<option value="80">80</option>
<option value="85">85</option>
<option value="90">90</option>
<option value="95">95</option>
<option value="100">100</option>
</select> <? echo '<button type="submit" value="' . $show['id']. '" name="submit">Bewerten?</button>'; }
elseif ($rolle == 9) {
echo '<button type="freigeben" value="' . $show['id']. '" name="freigeben">Freigeben?</button>';
echo '<button type="verwerfen" value="' . $show['id']. '" name="verwerfen">Verwerfen?</button><br><br>';
echo '<hr><br>'; ?>
E-Mail an Kunden schreiben:<br><textarea name ='informed' rows='8' cols='30' style="resize: none;"></textarea><br>
<? echo '<button type="informieren" value="' . $show['id']. '" name="informieren">Informieren?</button>';
}?></td>
</form>
I tried with an $i = 0; and then with a "if $i == 0 {} but, this is not working if a user has more than 1 project (the other project will not be displayed)
Thank you for your help!
Kind Regards, Stefan
I guess you want to display common text for all similar project images and id with It's related id & image.
You can do this by creating sub-array for managing image & id & main array for text description. Whenever same description received it'll break the loop & sub sequent data will be added as sub-array of main array. Try this. Hope it helps
$mainArry = array();
foreach($arrData as $item){
$idx = 0;
foreach($mainArry as $cat){
if($cat['text_description'] == $item['text_description']){
break;
}
$idx++;
}
$itemArry = array('id'=> ,'images' => );
if($idx >= 0){
$mainArry[$idx]['text_description'] = $item['text_description'];
$mainArry[$idx]['items'][] = $itemArry;
}
}
You should be doing a preprocessing of data (data massaging) before you use it for your template.
You can start by grouping rows with similar project
Example:
$processed_data = array();
foreach($rows as $row){
$processed_data[$row["project_id"][] = $row;
}
In this way, you can have something like this;
[
1 => [
[project 1, image1...]
[project 1, image2...]
[project 1, image3...]
],
2 => [
[project 2, image1...]
[project 2, image2...]
.....
]
]
Then in your template, it will be easier for you to display data with similar group
There are two methods I have mentioned below.
Please note that, these solutions are given based on following assumtions
1. You are using PHP
2. Database field names are userid, prjoject, text, image
3. You have stored imge src in the database.
Method 1:
SELECT userid, project,
GROUP_CONCAT(image separator ',') as images_list,
GROUP_CONCAT(image separator ',') as text_list
FROM your_table
GROUP BY userid,project
Above query returns data as you expected. Now you just need to populate those data into a html table.
Method 2:
Group data by user and project in your php code using a associative array.
$sql = "SELECT * FROM your_table";
Get query result to a PHP associative array. I assume the variable name is $data
$result = array();
foreach($data as $row) {
$userid = $row['userid'];
$project = $row['project'];
$result[$userid][$project]['text'][] = array('text' => $row['text'], 'image' => $row['image']);
}
HTML:
<table>
<?php foreach($result as $key_1 => $projects) { //userid holds $key_1 ?>
<?php foreach($projects as $key_2 => row ) {?>
<tr>
<td><?php echo $key_1; ?></td>
<td><?php echo $key_2; ?></td>
<td>
<table>
<tr><td><?php echo $row['text']?></td><tr>
<tr><td><img src="<?php echo $row['image']?>"></td><tr>
</table>
</td>
</tr>
<?php }?>
<?php } ?>
</table>
Following links may be helpful for more understanding.
MySql GROUP_CONCAT
PHP Associative array.
Hi thank you for your answers so far. I am nearly at the point where I could say "solved" :-)
$sql = "SELECT * from wp_awa_upload where stat = '0' order by parent_cat asc";
if (!$result = $mysqli->query($sql)) {
// Oh no! The query failed.
echo "Sorry, the website is experiencing problems.";
// Again, do not do this on a public site, but we'll show you how
// to get the error information
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$last_entry = null;
echo "<table width='100%' border='1' align='center'><tr>";
echo "<tr>";
echo "<td align='center'>Projektnamen</td>";
echo "<td align='center'>UID</td>";
echo "<td align='center'>Kategorie</td>";
echo "<td align='center'>Projektbeschreibung</td>";
echo "<td align='center'>Beschreibung</td>";
echo "<td align='center'>Copyright</td>";
echo "<td align='center'>Tools</td>";
echo "</tr>";
while ($row = $result->fetch_object()) {
echo "<tr>";
if ($last_entry != $row->project) {
echo "<td align='center'><textarea name ='project' rows='16' cols='30' style='resize: none'>".$row->project."</textarea></td>";
echo "<td align='center'>".$row->uid."</td>";
echo "<td align='center'>".$row->parent_cat."</td>";
echo "<td align='center'><textarea name ='project_desc' rows='16' cols='30' style='resize: none'>".$row->project_desc."</textarea></td>";
echo "<td align='center'><textarea name ='beschreibung' rows='16' cols='30' style='resize: none'>".$row->beschreibung."</textarea></td>";
echo "<td align='center'>".$row->copyright."</td>";
echo "<td align='center'>Buttons</td>";
echo "</tr>";
echo "<tr>";
$last_entry = $row->project;
}
//echo "<td align='center' colspan='6'><img src=".$row->url."<border='0'> </td>";
echo "<td align='center' colspan='7'>";
echo "<a href='".$row->url."' data-lightbox='".$row->file_name."' data-title='".$row->file_name."'><br><div class='center-cropped'><img src='".$row->url."' border='0'></a></div>";
}
echo "</tr>";
echo "</table>";
The Description, Category,... will be displayed only once, the images will be displayed, but not side by side - they will be displayed with a line break.
My Question: How can I display the images side by side (4 in a row?) As I could have up to 20 Images in a project, it would be nice to show them in a pack of 4 and a max. of 5 Rows.
Thank you for you help and assistance.
Kind Regards,
Stefan

how to insert multidimensional array using for loop

I have 2 tables. One is for students and one of subjects. I want to fetch data from the students and subjects tables on same page. In front of student 1 subject 1 subject 2 subject 3. Then in front of student 2 subject 1 subject 2 subject 3. It is to submit result.
I have done this.
Than I have to insert this in 3rd table of results. I have successfully inserted students in result table. And subjects. But on the time of marks, I am unable to insert. I used a multidimensional array. I am unable to insert marks data into array. How can I do this?
Let me show some snapshots.
My multidimensional array is not working, and I don't know how to do this. Kindly help me out.
This is a detailed pic: This is the detailed snapshot.
// count students
$sql = "SELECT * FROM tb_students";
$run = mysqli_query($mysqli,$sql);
$total_students = mysqli_num_rows($run);
$numbers=$total_students;
for($i=1;$i<=$numbers;$i++)
{
while ($rows = mysqli_fetch_assoc($run)) {
$id = $rows['student_id'];
$name = $rows['student_name'];
?>
<tr>
<td>Name</td>
<td hidden><input type="text" value="<?php echo $id?>" name="student_id[]" /></td>
<td><?php echo $name ?> </td>
</tr>
<input type="hidden" value="<?php echo $numbers;?>" name="numbers" />
<?php
$sel_sub = "SELECT * FROM subjects WHERE class_name = '1st year'";
$run_sub = mysqli_query($mysqli,$sel_sub);
$total_sub = mysqli_num_rows($run_sub);
for ($k=0; $k < $total_sub ; $k++) {
while ($rows = mysqli_fetch_assoc($run_sub)) {
$sub_id = $rows['sub_id'];
$sub_name = $rows['sub_name'];
?>
<tr>
<td><?php echo $sub_name; ?></td>
<td hidden><input type="" value="<?php echo $sub_id;?>" name="sub_id[]" /></td>
<input type="hidden" value="<?php echo $total_sub;?>" name="subject" />
<td><input type="text" name="marks[][]" placeholder="Marks" /></td>
</tr>
<?php
}
}
?>`
and this is isnert query
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
$sub_list = $_POST['marks'][$i][$j];
echo $sub_list;
}
}
mysqli_close($mysqli);?>
I don't want to say if this way is the best way.
But, your problem is you are using the lines in the loops which should not. Try this:
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
}
}
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
mysqli_close($mysqli);?>

MySQL php edition table and adding the same value on another table

I actually developping an intranet solution for my work,
The thing is that i want to update and operation and add the same result into one of my 3 different tables depending on the -operation- option,
in my initial code if the modification is ok the data will be updated into "taches_redaction" table,
in revenche i need to add 3 different rules,
soif operation is equal to 1 up date taches_redction and add the data into copie table,
soif operation is equal to 2 up date taches_redction and add the data into colla table,
soif operation is equal to 3 up date taches_redction and add the data into archive table,
all of this to have a precise historical record on echa changes in my operations and have some values to get statistics for each team member on the company...
<?php
include '../theme/header-global.php';
?>
<?php
/*
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, $error)
{
?>
<div style="width:100%">
<center><h1>تحيين التوزيع</h1></center>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="serie" value="<?php echo $serie; ?>" readonly="readonly" />
<table cellpadding="3" cellpadding="3" align="center" id=MyTable width="650">
<tr>
<td align="center">الإسم</td>
<td align="center">
<?php
// get results from database
$usage = mysql_query("SELECT t.* , o.* FROM users t,taches_redaction o WHERE t.id=o.user_id GROUP BY user_name")
or die(mysql_error());
while($row = mysql_fetch_assoc( $usage )) {
if($row['user_id'] == $user_id)
{ // echo out the contents of each row into a table
echo '' . $row['user_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<td>
<select id="user_id" name="user_id">
<option value="0"></option>
<?php
$sql = mysql_query('SELECT * FROM users');
while($row = mysql_fetch_array($sql)){
if($row['id'] == $user_id)
{
echo '<option value=' . $row['id'] . ' selected=selected>' . $row['user_name'] . '</option>';
} else {
// do something else
echo '<option value=' . $row['id'] . '>' . $row['user_name'] . '</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td align="center">اليومية</td>
<td align="center"><input type="text" name="journee" value="<?php echo $journee; ?>" /></td>
<td></td>
</tr>
<tr>
<td align="center">الرسم العقاري</td>
<td align="center">
<input type="text" name="titre" value="<?php echo $titre; ?>" />
<?php if (!empty($region) && $region == '4' ) echo 'FR'; ?>
<?php if (!empty($region) && $region == '1') echo 'بن عروس'; ?>
<?php if (!empty($region) && $region == '2') echo 'زغوان'; ?>
<?php if (!empty($region) && $region == '3') echo 'تونس'; ?>
</td>
<td>
<select name="region">
<option value="4" <?php if (!empty($region) && $region == '4' ) echo 'selected = "selected"'; ?>>FR</option>
<option value="1" <?php if (!empty($region) && $region == '1') echo 'selected = "selected"'; ?>>بن عروس</option>
<option value="2" <?php if (!empty($region) && $region == '2') echo 'selected = "selected"'; ?>>زغوان</option>
<option value="3" <?php if (!empty($region) && $region == '3') echo 'selected = "selected"'; ?>>تونس</option>
</select>
</td>
</tr>
<tr>
<td align="center">المهام</td>
<td align="center">
<select id="role" name="role">
<option value="0"></option>
<option></option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td align="center">العملية</td>
<td align="center">
<?php
$fonki = mysql_query("SELECT * FROM fonctions")
or die(mysql_error());
// get results from database
$operage = mysql_query("SELECT t.* , o.* FROM taches_redaction t,operations o WHERE t.operation=o.oper_id GROUP BY operation")
or die(mysql_error());
// display data in table
/* echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>"; */
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_assoc( $operage )) {
if($row['oper_id'] == $operation)
{ // echo out the contents of each row into a table
echo '' . $row['operation_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<?php
echo "<td>
<select name=operation>
<option value =0></option>";
include "../render/render_operation-selected.php";
echo "</select>
</td>";
?>
</tr>
<tr>
<td>تاريخ التحيين</td>
<td>
<?php
echo '' . $row['date'] . '';
?>
</td>
<td style="direction:rtl;">
<?php echo "<input type='text' value='".date('o/m/d')."' style='width: 148px;' name='date' readonly=readonly>";?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="تغيير" class="brd"></td>
<td align="center">
<input type="submit" value="إلغاء" onClick="history.go(-1);return true;" class="bbl">
</td>
</tr>
</table>
<?php
}
// connect to the database
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['serie']))
{
// get form data, making sure it is valid
$serie = $_POST['serie'];
$user_id = mysql_real_escape_string(htmlspecialchars($_POST['user_id']));
$journee = mysql_real_escape_string(htmlspecialchars($_POST['journee']));
$titre = mysql_real_escape_string(htmlspecialchars($_POST['titre']));
$region = mysql_real_escape_string(htmlspecialchars($_POST['region']));
$role = mysql_real_escape_string(htmlspecialchars($_POST['role']));
$operation = mysql_real_escape_string(htmlspecialchars($_POST['operation']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
// check that firstname/lastname fields are both filled in
if ($user_id == '' || $journee == '' || $titre == '' || $region == '' || $role == '' || $operation =='' || $date =='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($serie, $user_id, $journee, $titre, $region, $role , $operation, $date, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE taches_redaction SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date' WHERE serie='$serie'")
/* frere update */
/*
AND
mysql_query("INSERT copie SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT colla SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT archive SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
*/
or die(mysql_error());
// once saved, redirect back to the view page
/* header('Refresh: 2; URL = taches_view.php');
*/
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['serie']) && is_numeric($_GET['serie']) && $_GET['serie'] > 0)
{
// query db
$serie = $_GET['serie'];
$result = mysql_query("SELECT * FROM taches_redaction WHERE serie=$serie")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$serie = $row['serie'];
$user_id = $row['user_id'];
$journee = $row['journee'];
$titre = $row['titre'];
$region = $row['region'];
$role = $row['role'];
$operation = $row['operation'];
$date = $row['date'];
// show form
renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!-- end .content --></div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<?php
include '../theme/footer-global.php';
?>

Check a check box if it's value is in DB. PHP

I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.

Categories