I recently modified some code to allow for my quiz.php script to accommodate multiple quizzes as opposed to just one. To do this I sent along the quiz_id and quiz_title variables when the user clicks the link for the quiz and I receive them using $_GET. However, once the quiz form is submitted the quiz_id column no longer updates in the high_score table.
Here is the code for quiz.php
<?php
// Start the session
require_once('startsession.php');
// Insert the Page Header
$page_title = "Quiz Time!";
require_once('header.php');
require_once('connectvars.php');
// Make sure user is logged in
if (!isset($_SESSION['user_id'])) {
echo '<p>Please log in to access this page.</p>';
exit();
}
// Show navigation menu
require_once('navmenu.php');
// Connect to database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Declare $quiz_id
$quiz_title = $_GET['title'];
$quiz_id = $_GET['id'];
// print_r($quiz_title);
// print_r($quiz_id);
// Grab list of question_id's for this quiz
$query = "SELECT question_id FROM question WHERE quiz_id = '" . $quiz_id . "'";
$data = mysqli_query($dbc, $query);
$questionIDs = array();
while ($row = mysqli_fetch_array($data)) {
array_push($questionIDs, $row['question_id']);
}
// Create empty responses in 'quiz_response' table
foreach ($questionIDs as $questionID) {
$query = "INSERT INTO quiz_response (user_id, question_id) VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
mysqli_query($dbc, $query);
}
// If form is submitted, update choice_id column of quiz_response table
if (isset($_POST['submit'])) {
// Inserting choices into the response table
foreach ($_POST as $choice_id => $choice) {
$query = "UPDATE quiz_response SET choice_id = '$choice', answer_time=NOW() " .
"WHERE response_id = '$choice_id'";
mysqli_query($dbc, $query);
}
// Update the 'is_correct' column
// Pull all is_correct data from question_choice table relating to specific response_id
$total_Qs = 0;
$correct_As = 0;
foreach ($_POST as $choice_id => $choice) {
$query = "SELECT qr.response_id, qr.choice_id, qc.is_correct " .
"FROM quiz_response AS qr " .
"INNER JOIN question_choice AS qc USING (choice_id) " .
"WHERE response_id = '$choice_id'";
$data=mysqli_query($dbc, $query);
// Update is_correct column in quiz_response table
while ($row = mysqli_fetch_array($data, MYSQLI_ASSOC)) {
$total_Qs ++;
if ($row['is_correct'] == 1) {
$query2 = "UPDATE quiz_response SET is_correct = '1' " .
"WHERE response_id = '$row[response_id]'";
mysqli_query($dbc, $query2);
$correct_As ++;
}
}
}
// Update high_score table with $correct_As
$quiz_id = $_POST['quiz_id'];
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
mysqli_query($dbc, $query);
// Display score after storing choices in database
echo 'You got ' . $correct_As . ' out of ' . $total_Qs . ' correct';
exit();
mysqli_close($dbc);
}
// Grab the question data from the database to generate the form
$Q_and_Cs = array();
foreach ($questionIDs as $questionID) {
$query = "SELECT qr.response_id AS r_id, qr.question_id, q.question " .
"FROM quiz_response AS qr " .
"INNER JOIN question AS q USING (question_id) " .
"WHERE qr.user_id = '" . $_SESSION['user_id'] . "' " .
"AND qr.question_id = '" . $questionID . "'";
$data = mysqli_query($dbc, $query)
or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");
// Store in $questions array, then push into $Q_and_Cs array
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
print_r($row);
$questions = array();
$questions['r_id'] = $row['r_id'];
$questions['question_id'] = $row['question_id'];
$questions['question'] = $row['question'];
// Pull up the choices for each question
$query2 = "SELECT choice_id, choice FROM question_choice " .
"WHERE question_id = '" . $row['question_id'] . "'";
$data2 = mysqli_query($dbc, $query2);
while ($row2 = mysqli_fetch_array($data2, MYSQL_NUM)) {
$questions[] = $row2[0];
$questions[] = $row2[1];
}
array_push($Q_and_Cs, $questions);
}
}
mysqli_close($dbc);
// Generate the quiz form by looping through the questions array
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
echo '<h2>' . $quiz_title . '</h2>';
$question_title = $Q_and_Cs[0]['question'];
echo '<label for="' . $Q_and_Cs[0]['r_id'] . '">' . $Q_and_Cs[0]['question'] . '</label><br />';
foreach ($Q_and_Cs as $Q_and_C) {
// Only start a new question if the question changes
if ($question_title != $Q_and_C['question']) {
$question_title = $Q_and_C['question'];
echo '<br /><label for="' . $Q_and_C['r_id'] . '">' . $Q_and_C['question'] . '</label><br />';
}
// Display the choices
// Choice #1
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[0] . '" />' . $Q_and_C[1] . '<br />';
// Choice#2
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[2] . '" />' . $Q_and_C[3] . '<br />';
// Choice #3
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[4] . '" />' . $Q_and_C[5] . '<br />';
// Choice #4
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[6] . '" />' . $Q_and_C[7] . '<br />';
}
echo '<br /><br />';
echo '<input type="hidden" name="quiz_id" value"'.$quiz_id.'" />';
echo '<input type="submit" value="Grade Me!" name="submit" />';
echo '</form>';
// echo 'Quiz_id: '.$quiz_id.'<br />';
// Insert the page footer
require_once('footer.php');
?>
Here is the code for quizlist.php
// Determine number of quizes based on title in quiz table
$query = "SELECT * FROM quiz";
$data = mysqli_query($dbc, $query);
// Loop through quiz titles and display links for each
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
echo '' . $row['title'] . '<br />';
}
mysqli_close($dbc);
My problem has to do with the piece of code
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
It works when I substitute a number (i.e. 2) in the place of $quiz_id, but in order for the script to work for different quizzes I need to be able to use a different quiz_id for different quizzes.
I'm having trouble taking the variable from quizlist.php using $_GET and then passing it along as a hidden value when the form is submitted. Am I doing something incorrect? Or am I missing something completely obvious? I'd appreciate any help! Thanks...
On the first clue, it seems to me that you're getting your $quiz_id form GET request (and that's correct), but you have a condition
if (isset($_POST['submit'])) {
which is fulfilled only when form is submitted (POST request), not link clicked. So all the code under this condition is not executed when you click the link
Related
i cant seem to make each movie appear under their respective date and have a correct time dropdown menu for the movie time selection
$sql_date = "SELECT DISTINCT sDate, sTitle FROM movieScreenings ";
$result_date = mysqli_query($db, $sql_date);
while($row = mysqli_fetch_array($result_date)) {
echo "<h2>" . $row['sDate'] . "</h2>";
$sql_movie = "SELECT * FROM movieList, movieScreenings WHERE title = '" . $row['sTitle'] . "'";
$result_movie = mysqli_query($db, $sql_movie);
while($row2 = mysqli_fetch_array($result_movie)) {
echo "<div class='box'>
<img class='poster' src='posters/" . $row2['poster'] . "'/>
<h2>" . $row2['title'] . "</h2>
<p>" . $row2['description'] . "</p>";
$sql_time = "SELECT DISTINCT sTime FROM movieScreenings WHERE sTitle = '" . $row2['title'] . "' AND sDate = '" . $row['sDate'] . "'";
$result_time = mysqli_query($db, $sql_time);
while($row3 = mysqli_fetch_array($result_time)) {
echo "<select name='sTime'>
<option value='" . $row3['sTime'] . "'>" . $row3['sTime'] . "</option>
</select>";
echo "</div>";
}
}
}
mysqli_free_result($result_date);
mysqli_free_result($result_movie);
mysqli_free_result($result_time);
// Close connection
mysqli_close($db);
You probably want to sort your first query by sDate with ORDER BY sDate.
In your second query you are again selecting from movieScreenings which is not necessary because I imagine all the data you are accessing (poster, title, description) is stored in movieList.
Thirdly, in your last while loop you are repeating the <select> tag for every screening time. This will result in multiple dropdown inputs. Also, you are including the closing </div> tag in this loop. So only loop the <option> tag.
With these changes your code would look like this:
$sql_date = "SELECT DISTINCT sDate, sTitle FROM movieScreenings ORDER BY sDate ASC";
$result_date = mysqli_query($db, $sql_date);
while($row = mysqli_fetch_array($result_date)) {
echo "<h2>" . $row['sDate'] . "</h2>";
$sql_movie = "SELECT * FROM movieList WHERE title = '" . $row['sTitle'] . "'";
$result_movie = mysqli_query($db, $sql_movie);
while($row2 = mysqli_fetch_array($result_movie)) {
echo "<div class='box'>
<img class='poster' src='posters/" . $row2['poster'] . "'/>
<h2>" . $row2['title'] . "</h2>
<p>" . $row2['description'] . "</p>";
$sql_time = "SELECT DISTINCT sTime FROM movieScreenings WHERE sTitle = '" . $row2['title'] . "' AND sDate = '" . $row['sDate'] . "'";
$result_time = mysqli_query($db, $sql_time);
echo "<select name='sTime'>";
while($row3 = mysqli_fetch_array($result_time)) {
echo "<option value='" . $row3['sTime'] . "'>" . $row3['sTime'] . "</option>";
}
echo "</select>";
echo "</div>";
}
}
...
And lastly, I would suggest using ID's as your foreign keys to prevent duplicates in the future. There might be multiple movies with the same title.
I have a table in which two text fields and one input text field. A query is created new row, and if there is one, just update.
if (isset($_POST['submit'])) {
$text = !empty($_POST['text']) ? $_POST['text'] : null;
foreach ($text as $idt => $pages) {
if ($pages != NULL) {
$todb = $mysqli->query('INSERT INTO extendtovar (book_id, pages)
VALUES ("' . $idt . '", "' . $pages . '")
ON DUPLICATE KEY UPDATE pages = "' . $pages . '"');
}
}
}
$todb = $mysqli->query('SELECT
nalvmag.id AS id,
nalvmag.name AS name,
extendtovar.book_id AS id2,
extendtovar.pages AS pages
FROM nalvmag LEFT JOIN extendtovar
ON nalvmag.id = extendtovar.book_id
WHERE nalvmag.remainder > 0
ORDER BY name ASC');
echo '<table class="raz">';
while ($row = $todb->fetch_array())
{ echo '<tr><td>'.$row[id].'</td>';
echo '<td>'.$row[name].'</td>';
echo '<td><input type="text" name="text['.$row[id].']" value="'.$row[pages].'" maxlength="5" size="6"><br></td></tr>';
}
echo '</table>';
echo'<button type="submit" name="submit">Submit</button></form>';
}
But now I want to add one more input text field
echo $row[id];
echo row[name];
echo '<input type="text" name="text['.$row[id].']" value="'.$row[pages].'" maxlength="5" size="6">
echo '<input type="text" name="text2['.$row[id].']" value="'.$row[pages2].'" maxlength="5" size="6">
and when i update php code to
if (isset($_POST['submit'])) {
$text = !empty($_POST['text']) ? $_POST['text'] : null;
foreach ($text as $idt => $pages) {
if ($pages != NULL) {
$todb = $mysqli->query('INSERT INTO extendtovar (book_id, pages, pages)
VALUES ("' . $idt . '", "' . $pages . '", "' . $pages2 . '")
ON DUPLICATE KEY UPDATE pages = "' . $pages . '", pages2 = "' . $pages2 . '"');
}
}
}
field pages2 not update.
I can not understand how to properly change foreach and form a request
So this is a part from the administrator page.
After several modifications I came to this, which is the best I could get unfortunately:
<?php
$sql = "SELECT name
FROM users";
$result = mysqli_query($connection, $sql);
$users = array();
while ($row = mysqli_fetch_assoc($result))
{
$users[] = $row["name"];
}
echo ('</br><form action="" method="POST" style="display:inline!important"></br>
<select name="deleteUser">
<option value="' . $users[1] . '">' . $users[1] . '</option>' .
'<option value="' . $users[2] . '">' . $users[2] . '</option>' .
'<option value="' . $users[3] . '">' . $users[3] . '</option>' .
'<option value="' . $users[4] . '">' . $users[4] . '</option>' .
'<input class="w3-bar-item w3-button w3-hide-small w3-hover-green" type="submit" value="Delete" name="delete"></select></form>');
if (isset($_POST["delete"]))
{
$sql = "DELETE
FROM users
WHERE name = '" . $_POST["deleteUser"] . "'";
mysqli_query($connection, $sql);
}
?>
I tried to write a loop to generate the select options like this:
<?php
$sql = "SELECT name
FROM users";
$result = mysqli_query($connection, $sql);
$users = array();
while ($row = mysqli_fetch_assoc($result))
{
$users[] = $row["name"];
}
echo ('</br><form action="" method="POST" style="display:inline!important"></br>
<select name="deleteUser">');
for ($i = 0; $i < count($users); $i++)
{
echo('<option value="' . $users[$i] . '">' . $users[$i] . '</option>');
}
echo('<input class="w3-bar-item w3-button w3-hide-small w3-hover-green" type="submit" value="Delete"></select></form>');
if (isset($_POST["delete"]))
{
$sql = "DELETE
FROM users
WHERE name = '" . $_POST["deleteUser"] . "'";
mysqli_query($connection, $sql);
}
?>
But the browser doesn't render it(i.e Chrome), maybe because it just can't on portions? Like to wait for the loop to complete and then to end with the last part of the form.
Anyway, how could I make it work? Thanks mates...
Instead of using while loop you can use foreach this is where you can use foreach properly
Here is an example that might help you
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
foreach($rows as $val){
//Here populate your options like this
echo '<option> '.$val["name"].' </option'
}
Hope this will help you out :)
I have some PHP displaying an HTML form like this:
And then updates the information in the table when the update button is pressed.
My issue is with the delete option. Any time I hit the update button, the information IS updated successfully, but I get this error message about the delete statement:
Here is the code:
// Info to connect to the Wishlist database
$servername = ".com";
$dbusername = "";
$password = "";
$dbname = "";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "Please click <strong><a href = 'http://eggcavity.com/add-wishlist'>here</a></strong> to add creatures to your wishlist.";
if(isset($_POST['submit'])){
$ids = $_POST['ids'];
// Prepare and bind the udpate statement
$sql2 = "UPDATE Wishlists SET Picture = ?, Stage = ?, Gender = ?, Frozen = ?, Notes= ? WHERE ID = ?";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('sssssi', $picture, $stage, $gender, $frozen, $notes, $id);
foreach($ids as $id){
$stagecode = $id . "stage";
$gendercode = $id . "gender";
$frozencode = $id . "frozen";
$notescode = $id . "notes";
$namecode = $id . "creature";
$stage = $_POST[$stagecode];
$Stage = $stage;
$gender = $_POST[$gendercode];
$frozen = $_POST[$frozencode];
$notes = $_POST[$notescode];
$name = $_POST[$namecode];
$sql1 = 'SELECT * FROM Creatures WHERE Name = "' . $name . '"';
$result = mysqli_query($conn, $sql1);
$row = $result->fetch_assoc();
$picture = $row["$stage"];
$stmt2->execute();
}
$theCount = 0;
foreach($_POST['delete'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
echo "Your wishlist has been updated, and" .$theCount. " creature(s) has/have been removed from your wishlist.<br>Please click <a href='http://eggcavity.com/edit-wishlist'>here</a> to return to the edit page.";
} else {
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
$theDeleteCount = 0;
// Just display the form
$sql = 'SELECT Creature, Picture, Stage, Gender, Frozen, ID FROM Wishlists WHERE Username = "' . $username . '"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="POST"><table><strong>' .
'<tr>' .
'<td></td>' .
'<td>Creature</td>' .
'<td>Stage</td>' .
'<td>Gender</td>' .
'<td>Frozen</td>' .
'</tr></strong>';
while($row = $result->fetch_assoc()) {
$creature = $row["Creature"];
$id = $row["ID"];
$picture = $row["Picture"];
$stage = $row["Stage"];
echo '<input name="ids[]" type="hidden" value="' . $id . '">' .
'<input name="' . $id . 'creature" type="hidden" value="' . $creature . '">' .
'<tr>' .
'<td rowspan="2"><img src="' . $picture . '"></td>' .
'<td>' . $creature . '</td>' .
'<td><select name="' . $id . 'stage">' .
'<option value ="' . $stage . '" selected>' . $stage . '</option>' .
'<option value = "Stage1">Stage1(Egg)</option>' .
'<option value = "Stage2">Stage2</option>' .
'<option value = "Stage3">Stage3</option>' .
'<option value = "Stage4">Stage4</option>' .
'</select></td>' .
'<td><select name="' . $id . 'gender">' .
'<option value ="' . $row["Gender"] . '" selected>' . $row["Gender"] . '</option>' .
'<option value = "Unspecified">Unspecified</option>' .
'<option value = "Female">Female</option>' .
'<option value = "Male">Male</option>' .
'</select></td>' .
'<td><select name="' . $id . 'frozen">' .
'<option value ="' . $row["Frozen"] . '" selected>' . $row["Frozen"] . '</option>' .
'<option value="Unspecified">Unspecified</option>' .
'<option value="Yes">Yes</option>' .
'<option value="No">No</option>' .
'</select></td>' .
'</tr>' .
'<tr>' .
'<td colspan="3">Notes: <input type="text" name="' . $id . 'notes" value="' . $row["Notes"] .'"></td>' .
'<td>' . 'Delete<br>' . '<input type="checkbox" name="creatures[]" value="' . $id . '"></td>' .
'</tr>';
}
echo '</table><input name="submit" type="submit" id="submit" value="Update"></form>';
} else {
echo "<br>You have no creatures in your wishlist.";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
// Close the connection to the database
$conn->close();
If you could please help me find what is wrong with the information I am passing to the foreach() statement:
foreach($_POST['delete'] as $selected){
I would be forever grateful. Any idea helps.
I have tried a few many things, a lot of which were found on stackoverflow. I think I am probably missing something small and/or stupid. I have another page running off of a checkbox form which works just fine.
Thank you and have a great day!
The form element that contains the ids of cratures to be deleted is called creatures[] so you need to process the contents of that POST variable rather than delete - even though delete is what you wish to do. SO, perhaps something like this:-
Replace
$theCount = 0;
foreach($_POST['delete'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
with
$theCount = 0;
$creatures=!empty( $_POST['creatures'] ) ? $_POST['creatures'] : false;
if( $creatures ) {
if( !is_array( $creatures ) ) $creatures=explode(',',$creatures);
foreach( $creatures as $id ){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$theCount++;
}
}
if deleting is optional every time then just put an variable check like
if(isset($_POST['creatures']))
{
foreach($_POST['creatures'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
}
this code will run only when it finds $_POST['creatures'] means ur checkbox is checked
I'm getting the error message in the title for the following code, the page is for adding sub categories to my forum.
<?php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>" . $sub_cat_name . "</b> has been added under the main category <b>" . $cat_name . "</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
echo 'New Sub category succesfully added.';
}
}
}
; ?>
My categories table is structured like so..
cat_id
cat_desc
My subcategories table is structured like so..
id(AI)
c_id
sub_cat_name
sub_desc
If I haven't provided enough information please let me know.
You've not quoted things properly here:
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
You need
VALUES('" . $cat_id . "', '" . $sub_cat_name . "', '" . $sub_desc . "')";
Note the extra single quotes.
You missed some quotes. Change
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
to
VALUES('" . $cat_id . "', '" . $sub_cat_name . "', '" . $sub_desc . "')";