<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<p>A | B | C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z </p>
<p>You may also search by Patrol.</p>
<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="patrol">
<input type="submit" name="submit" value="Search">
</form>
<?php
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect("localhost", "*****", "*****");
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db("troop97_***");
if (!$db) {
die("Unable to select database");
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['name'])) {
$name = $_POST['name'];
//-query the database table
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string($name) . "%' OR Last_Name LIKE '" . mysql_real_escape_string($name) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . stripslashes($name) . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
} else {
echo "<p>Please enter a search query</p>";
}
}
}
if (isset($_GET['by'])) {
$letter = $_GET['by'];
//-query the database table
$letter = mysql_real_escape_string($letter);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . $letter . "%'
OR Last_Name LIKE '" . $letter . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $letter . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['patrol'])) {
$patrol = $_POST['patrol'];
//-query the database table
$patrol = mysql_real_escape_string($patrol);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE Patrol LIKE '" . mysql_real_escape_string($patrol) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $patrol . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_GET['id'])) {
$contactid = $_GET['id'];
//-query the database table
$sql = "SELECT * FROM contact WHERE ID=" . $contactid;
//-run the query against the mysql query function
$result = mysql_query($sql);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$Home_Phone = $row['Home_Phone'];
$Cell_Phone = $row['Cell_Phone'];
$Work_Phone = $row['Work_Phone'];
$Email = $row['Email'];
$Home_Street = $row['Home_Street'];
$Home_City = $row['Home_City'];
$Home_State = $row['Home_State'];
$Home_Zip = $row['Home_Zip'];
$Troop_Role = $row['Troop_Role'];
$Patrol = $row['Patrol'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . $First_Name . " " . $Last_Name . "</li>\n";
echo (empty($Home_Phone)) ? '' : "<li>" . $Home_Phone . " Home</li>\n";
echo (empty($Cell_Phone)) ? '' : "<li>" . $Cell_Phone . " Cell</li>\n";
echo (empty($Work_Phone)) ? '' : "<li>" . $Work_Phone . " Work</li>\n";
echo "<li>" . "" . $Email . "</li>\n";
echo "<li>" . $Home_Street . "</li>\n";
echo "<li>" . $Home_City . ", " . $Home_State . " " . $Home_Zip . "</li>\n";
echo "<li>" . $Troop_Role . "</li>\n";
echo "<li>" . $Patrol . "</li>\n";
echo "</ul>";
}
}
}
}
SQL Injection Risk
If you ever use a value from a submitted form when interacting with a database, you should escape the content before doing so. In MySQL, the best function to do this is mysql_real_escape_string() PHP Manual
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string( $name ) . "%' OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%'";
Adding Fields to Search
If you are wanting to add an additional field, like "Department" to the search query, you simply have a field on the search form corresponding to it, and then adapt your SQL Search to have it included in the WHERE clause:
$sql="SELECT ID, First_Name, Last_Name
FROM contact
WHERE ( First_Name LIKE '" . mysql_real_escape_string( $name ) . "%'
OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%' )
AND Department='" . mysql_real_escape_string( $department ) ."'";
Using One Field for Two Searches
If you wanted to use a single text field to perform the above search, you will need to decide on some kind of prefix for users to prefix the value for the second field with.
For instance, if we specify "in:" as a prefix to designate the Department, so a search for "John in:Radiology" would look for any person with a first, or last, name starting with "John" but only those in the "Radiology" department.
list( $name , $department ) = explode( ' in:' , $_POST['name'] , 2 );
instead of
$name = $_POST['name'];
LIKE Search Limitation
At the moment, your code will only search for First Names and/or Last Names which start with the entered value. You can make the search return either fields which simply contain (not just start with) the entered value by putting another "%" at the start of the search string:
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '%" . $name . "%' OR Last_Name LIKE '%" . $name ."%'";
Full-Text Search
You may want to look at this tutorial - Using MySQL Full-text Searching. It covers the concepts of Full-Text Searching, will allows you to find one, or more, words submitted through a single field across multiple database fields.
Limit Returned Rows
Always a good idea to limit the number of rows you return for a search, whether you paginate or simply show X rows. Failing to do this would allow a malicious user to essentially scrape your whole database by simple searching for each letter of the alphabet.
Add your hypothetical field say search_field and then search for it with "SELECT * FROM contact WHERE search_field='search value' order by First_Name", don't forget to index on search_field if it is going to be a unique field like email. I hope the code you pasted above will not go into production. Do not trust user inputs and filter them properly before you used them in SQL queries, needless to say store db credentials and connection string in a separate file and include it.
Related
How can i display search results using mysqli multiquery. I want to display values from my listing-details table and from my user table. Here is my code:
$searchquery="SELECT * FROM `listing-details` WHERE `listing-address` LIKE '%" . $address . "%' AND `listing-address-street` LIKE '%" . $street . "%' AND `listing-address-barangay-id` LIKE '%" . $barangay . "%'";
$searchquery.= "SELECT `user.user-username`, `user.user-firstname`, `user.user-lastname`, `listing-details.user-username` FROM `user`, `listing-details` WHERE `listing-details.user-username`=`user.user-username`";
if (mysqli_multi_query($conn, $searchquery)) {
do {
if ($result=mysqli_store_result($conn,$searchquery)){
while($row=mysqli_fetch_row($result)){
$listingid =$row['listing-id'];
$username =$row['user-username'];
$listingbedquantity =$row['listing-bedquantity'];
$listingbedtype =$row['listing-bedtype-id'];
$listingguestsquantity =$row['listing-guestsquantity'];
$listingplacetype =$row['listing-placetype-id'];
$listingpropertytype =$row['listing-propertytype-id'];
$listingbathroomquantity =$row['listing-bathroomquantity'];
$listingaddress =$row['listing-address'];
$listingstreet =$row['listing-address-street'];
$listingbarangay =$row['listing-address-barangay-id'];
$listingamenities =$row['listing-amenities-basic-id'];
$listingsafetyamenities =$row['listing-amenities-safety-id'];
$listingsaphotos =$row['listing-amenities-safety-photos-id'];
$listingspace =$row['listing-space-id'];
$listinglandmark =$row['listing-landmark'];
$listingpreferences =$row['listing-preferences-id'];
$listingphotoset =$row['listing-photosset-id'];
$listingexperience =$row['listing-experience-id'];
$listingfrequency =$row['listing-frequency-id'];
$listingstartdate =$row['listing-startdate'];
$listingrate =$row['listing-rate-id'];
$listingprice =$row['listing-price'];
$listingrules =$row['listing-rules-id'];
$listingtitle =$row['listing-title'];
$listingdescription =$row['listing-description'];
$firstname =$row['user-firstname'];
$lastname =$row['user-lastname'];
echo "<ul>\n";
echo "<li>"."" . "<h2>" . $listingtitle . "</h2></li>\n";
echo "<li><h6>" . $listingaddress . ", " . $listingstreet . ", " . $listingbarangay . "</h6></li>";
echo "<li><i>" . $listingdescription . "</i></li>";
echo "<ul>\n";
echo "<li>"."" . "<h2>" . $listingtitle . "</h2></li>\n";
echo "<li><h6>" . $listingaddress . ", " . $listingstreet . ", " . $listingbarangay . "</h6></li>";
echo "<li><i>" . $listingdescription . "</i></li>";
echo "<li style='float:right;'>By: " . $firstname . " " . $lastname . "</i></li>";
echo "</ul>";
echo "<hr width='80%' noshade='1'>";
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($conn));
}
However, when I get to run it,the page loads, but results won't show. The purpose of it is to be able to display listing details from a listing-details table listed by the complete name from the user table. Two two tables have user-username column as common key.
Like many learners, you are using the wrong tool, simply because you don't know the proper one.
You need not a multiquery (which you never actually need anyway) but a JOIN.
Simply rewrite your two monster queries to a join like this
$searchquery="SELECT l.*, u.`user-username`, u.`user-firstname`, u.`user-lastname`
FROM `listing-details` l, user u
WHERE l.`user-username`=u.`user-username`
AND `listing-address` LIKE ...";
Besides, your quoting is wrong.
I am new to PHP and Mysql programming and I would like to know if I can access another database row when showing data in a form.
Here is the code:
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);
$result = mysqli_query($con, "SELECT * FROM Elev WHERE Clasa = '" . $_SESSION['clasa'] . "' ORDER BY Nume ASC ");
$result2 = mysqli_query($con, "SELECT * FROM M_Profesori WHERE ID = '" . $_SESSION['ID_p'] . "' ");
while ($row2 = mysqli_fetch_array($result2)) {
while ($row = mysqli_fetch_array($result)) {
echo "<select>
<option value='" . $row2["Materia"] . "'>" . $row2["Materia"] . "</option>
<option value='" . $row2["Materia"] . "'>" . $row2["Materia"] . "</option>
</select>";
}
}
In the second option (<option value='" . $row2[Materia] . "'>" . $row2[Materia] . "/option>) I would like to access the next database row, not this one. Is this possible?
If I've understood, you can try this:
$row2 = mysqli_fetch_array($result2);
foreach($row2 as $key => $value) {
...
<option value='" . $row2[$key+1][Materia] . "'>" . $value . "</option>
...
}
try this...
In adicional, look this:
You can use a template to build better codification. (site in portuguese)
http://raelcunha.com/template.php
http://raelcunha.com/packages/extra/template/pt-br/api/index.php
I am trying to make an advanced search engine, one in which you can search by first name, last name, zip, city, state, phone, cell phone and email.
I have managed to get it to search by first name, but you have to type the first name correctly as with anything else, I took out everything else but the first name search to find my problem yet, I have yet to find it, Here is a MySQL version of my search code that I am trying to convert to PDO.
MySQL:
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes") {
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
if ($f == "")
if ($info == "")
if ($zip == "")
if ($state == "")
if ($email == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("xxx", "xxxx", "xxx") or die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());
// We preform a bit of filtering
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE fname
LIKE '%" . mysql_real_escape_string($find) . "%' AND lname
LIKE '%" . mysql_real_escape_string($f) . "%' AND info
LIKE '%" . mysql_real_escape_string($info) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND email
LIKE '%" . mysql_real_escape_string($city) . "%' AND city
LIKE '%" . mysql_real_escape_string($email) . "%'");
?>
<?php
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<hr><br>First Name: ";
echo $result['fname'];
echo "<br>Last Name: ";
echo $result['lname'];
echo "<br>Home Phone: ";
echo $result['info'];
echo "<br>Cell Phone: ";
echo $result['cp'];
echo "<br>City: ";
echo $result['city'];
echo "<br>State: ";
echo $result['state'];
echo "<br>Zip: ";
echo $result['zip'];
echo "<br>Email: ";
echo $result['email'];
echo "<br><hr>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:
</b> " .$find;
}
?>
Now here is my PDO version:
<?
$dsn = 'mysql:host=xxx;dbname=xxx;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'xxx','xxx', $opt);
$stmt = $pdo->prepare("SELECT * FROM users WHERE fname= ?");
if ($stmt->execute(array($fname)));
while ($row = $stmt->fetch()) {
print $row['fname'] . "<br>";
print $row['lname'] . "\t<br>";
print $row['info'] . "\n<br>";
print $row['cp'] . "\n<br>";
print $row['state'] . "\n<br>";
print $row['city'] . "\n<br>";
print $row['zip'] . "\n<br>";
print $row['email'] . "\n<br>";
}
?>
Tips, advice, and comments are welcome and appreciated.
I guess you would build a sql-string and use parameters.
You would not include into your sql fields that the user left empty.
// **EDIT** check if there's any user-input...
if (!isset($_POST['fname']) && !isset($_POST['lname'])) { // add all your input-fields
echo "<p>please enter a search term!</p>";
echo 'try again";
exit();
}
$sql = '';
$bind = array();
if (strlen($_POST[‘firstname‘]) > 0) { // assuming your form-method is "post"
$sql .= 'AND fname LIKE :fname ';
$bind['fname'] = '%'.$_POST['firstname'].'%';
}
if (strlen($_POST['lastname']) > 0)
$sql .= 'AND lname LIKE :lname ';
$bind['lname'] = '%'.$_POST['lastname'].'%';
}
// ...
// do this will all of your input-fields...
$sql = 'SELECT * FROM users WHERE ' . trim($sql, 'AND') . ' ORDER BY lname';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($bind));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// go ahead and display your results with foreach...
Your biggest problem is you’re using AND instead of OR in your WHERE clause. Change it to this:
SELECT *
FROM `table`
WHERE `name` LIKE '%string%'
OR `zip` LIKE '%string%'
// AND SO ON
The list just stayed at ten items with no pagination to get the rest of the other list, this sucks, But thanks Guys, maybe i need more practice i really need this one to be working so i can learn from this one, any way the first code worked, the second works but stops at ten items, you said try the ceil i did with some code that i had already, the next and back and number of pages came up but no list, tried it again no next and back but ten items came up, i'm beginning to get a bit frustrated here.
<DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Residential</title>
</head>
<body>
<section>
<form method="post" action="index.php?go" id="searchform">
<input type="text" id="sf" name="name" class="inputtext" >
<input type="submit" name="submit" id="sb" alt="Btn" value="GO">
</form>
</section>
<div class="results">
<?php
error_reporting(0);
if(isset($_POST['submit'])) {
if(isset($_GET['go'])) {
if(preg_match("/[A-Z | a-z]+/", $_POST['name'])){ //"/[A-Z | a-z]+/",
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("residential");
This is the beginning of the changed code
//////////pagination////////////
$sql=mysql_query("SELECT userId, FirstName, LastName FROM residentialbackup WHERE FirstName ='" . $name . "' OR LastName = '" . $name ."'");
//-count results
$numrows=mysql_num_rows($sql);
// Get the value of the last page in the pagination result set
$lastPage = ceil($numrows / $itemsPerPage);
$itemsPerPage = 10;
$page = $_GET['page'];
if (!$page) $page = 1;
$offset = ($page - 1) * $itemsPerPage;
$sql2=mysql_query("SELECT userId, FirstName, LastName FROM residentialbackup WHERE FirstName = '" . $name . "' OR LastName = '" . $name ."' LIMIT ". $offset . ", ". $itemsPerPage);
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1") {
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $page . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($page != 1) {
$previous = $page - 1;
$paginationDisplay .= ' Back ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($page != $lastPage) {
$nextPage = $page + 1;
$paginationDisplay .= ' Next ';
}
}
echo $paginationDisplay;
///////////////pagination end////////////
i'm stuck up to here!
//echo "<p>" .$numrows . " results found for " . stripslashes($name) . "</p>";
//-create while loop and loop through result set
while($row=mysql_fetch_array($sql2)) {
$FirstName =$row['FirstName'];
$LastName=$row['LastName'];
$userId=$row['userId'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$FirstName . " " . $LastName . " </li>\n";
echo "</ul>";
}
}
else {
echo "<p>Please enter a search query</p>";
}
}
/*
if(isset($_GET['by'])){
$name=$_GET['by'];
include "connectres.php";
//-query the database table
$sql="SELECT userId, FirstName, LastName FROM residentialbackup WHERE FirstName LIKE '%" . $name . "%' OR LastName LIKE '%" . $name ."%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-count results
$numrows=mysql_num_rows($result);
echo "<p>" .$numrows . " results found for " . $name . "</p>";
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$FirstName =$row['FirstName'];
$LastName=$row['LastName'];
$userId=$row['userId'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . " " . $LastName . " " . $FirstName . " </li>\n";
echo "</ul>";
}
}
*/
if(isset($_GET['id'])) {
$userId=$_GET['id'];
//connect to the database
include "connectres.php";
//-query the database table
$sql="SELECT * FROM residentialbackup WHERE userId=" . $userId;
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)) {
$FirstName =$row['FirstName'];
$LastName=$row['LastName'];
$PhoneNumber=$row['PhoneNumber'];
$Address=$row['Address'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "<img src=\"../images/person.png\"/>" . $FirstName . " " . $LastName . " </li>\n";
echo "<li>" . "<img src=\"../images/tell.png\"/>" . " " . "" . $PhoneNumber . "</li>\n";
echo "<li>" . "<img src=\"../images/house.png\"/>" . " " . $Address . "</li>\n";
echo "</ul>";
}
}
?>
</div>
</div>
</body>
</html>
Your query has wildcards in it, remove them to only fetch exact matches
$sql="SELECT userId, FirstName, LastName FROM residentialbackup WHERE FirstName ='" . $name . "' OR LastName = '" . $name ."'";
You can make a pagination like this:
$itemsPerPage = 10;
$page = $_GET['page'];
if (!$page) $page = 1;
$offset = ($page - 1) * $itemsPerPage;
$sql="SELECT userId, FirstName, LastName FROM residentialbackup WHERE FirstName = '" . $name . "' OR LastName = '" . $name ."' LIMIT ". $offset . ", ". $itemsPerPage;
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