Sum Up Points Based on Questions Answered - php

The code is of a short-answer quiz for a uni course. What I'd like to do is to match students' response to answer stored in database. A matching answer (or keywords) counts as a point. I'm having trouble counting the total points. The preg_match() results are already correct. Here is the code:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
?>
<head></head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="590" border="1" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//echo $ins_id;
//$correct = 0;
$total = 0;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans[] = $_POST[$repStr];
//echo $ans;
$sql_check = "SELECT q_ans FROM question WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (s_id, q_id, response, response_value, created) VALUES ('" . $id . "', '" . $i . "', '" . $ans . "', '" . $correct . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
}
// insert result to table
//$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('" . $total . "','" . $id . "','" . $ins_id . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_ans, q_help FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions & answers
$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
echo "<tr><td width='20' align='center' valign='top'><label><br><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><p align='justify'>". $data_q['q_text'] ."<br />";
if(preg_match_all("/". $ans[$arr_ind]. "/i", " . $atext[$arr_ind] . ")){
echo "Something matches";
$total = total + 1;
}
//else if (preg_match("/^$/", " . $atext[$arr_ind] . "))
//echo "Empty string";
else
echo "Wrong";
echo "<p align='justify'><b>YOUR ANSWER: </b>". $ans[$arr_ind]. "</p>";
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$rad++;
$arr_ind++;
}
mysql_free_result($query_q);
include("dbconn.php");
echo "</table>";
echo "<h2>" . $total . " questions correct. - Answer Review</h2>";
echo "</form>";
?>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
// close db connection
mysql_close($dbconn);
?>

You are missing a $ in:
$total = total + 1;
Or just use:
$total++;

Related

how do I make this page work it just redirects to homepage

I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end

Cant get table to update, delete and add with an extra code

So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>

Php page not displaying

I am having a problem displaying a JOIN statement. When I add
WHERE id = " . $team_id;
The information that is on the database will not display, but when I remove that line the information will correctly join and display on the "teaminfo.php " page, but it will display all of the data instead of the data that is unique to that id. Also when I remove the JOIN the the data that is unique to the id will display. Can anyone tell me whats wrong here. Any help will be great. Than you.
teaminfo.php
<html>
<head>
<title>Team Info page</title>
</head>
<body>
<?php
include 'connect.php';
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
if ($result = mysqli_query($mysqli, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
// Write the data of the team
echo "<br />";
echo "Pit scouting";
echo "<dt>Team:</dt><dd>" . $row["pteam_number"] . " " . $row["pteam_name"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["pauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["pdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["pobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["pobjWithProblem"] . "</dd>";
echo "<dt>Can they shoot? If yes from where and how acc</dt><dd>" . $row["pshoot"] . "</dd>";
echo "<dt>Extra Notes about their robot?</dt><dd>" . $row["pdrive"] . "</dd>";
echo"<br />";
echo "Field Scouting ";
echo "<dt>Team Number:</dt><dd>" . $row["fteam_number"] . "</dd>";
echo "<dt>Auto:</dt><dd>" . $row["fauto"] . "</dd>";
echo "<dt>Drive:</dt><dd>" . $row["fdrive"] . "</dd>";
echo "<dt>Objetcs With No Problem?</dt><dd>" . $row["fobjNoProblem"] . "</dd>";
echo "<dt>Objects They have a problem with?</dt><dd>" . $row["fobjWithProblem"] . "</dd>";
echo "<dt>Shots taken</dt><dd>" . $row["fshots_taken"] . "</dd>";
echo "<dt>Shorts made</dt><dd>" . $row["fshots_made"] . "</dd>";
echo "<dt>Extra Notes</dt><dd>" . $row["fnotes"] . "</dd>";
}
mysqli_free_result($result);
}
// Close the database connection
mysqli_close($mysqli);
?>
<p>Return to the list</p>
</body>
</html>
Palmetto.php
<?php
include 'connect.php';
// SQL query
$query = "SELECT * FROM pitscouting ORDER BY pteam_number";
if($result = mysqli_query($mysqli, $query)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$name = $row['pteam_number'] . " " . $row['pteam_name'];
// Create a link to teaminfo.php with the id-value in the URL
$strLink = "<a href = 'teaminfo.php?id= " . $row['id'] . "'>" . $name . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $query. " . mysqli_error($mysqli);
}
// Close connection
mysqli_close($mysqli);
?>
If your tables both have an ID field you will have to specify which table you want to get the data from.
WHERE pitscouting.id = " . $team_id;
or
WHERE fieldscouting.id = " . $team_id;
Please do mention the sql injection in you're code
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting
JOIN fieldscouting
ON pteam_number = fteam_number
WHERE id = " . $team_id;
please take a look at prepared statements, to prevent sql injections in youre code
Try putting an alias.
$team_id = $_GET['id'];
// SQL query
$query = " SELECT *
FROM pitscouting p
JOIN fieldscouting f
ON p.pteam_number = f.fteam_number
WHERE p1.id = " . $team_id;

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

why does the error message not show up?

I am very new to PHP (only been doing it since September so I apologise if this seems like a silly question, I'm very stuck and can't work out the answer!) and cannot work out why my error message does not display when a user submits the form when it is empty.
This is my code:
<?php
$salonid = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
//Capture form data, if anything was submitted
if (isset($_GET['salonid']) and ($_GET['salonid'] != '')){
$salonid = clean_string($db_server, $_GET['salonid']);
//If connected, get Salons from database and write out
mysqli_select_db($db_server, $db_database);
$query = "SELECT ID, salon_name, address, postcode, telephone, email, website FROM salon WHERE ID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Query failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_result .= "<h2>" . $row[ 'salon_name'] . "</h2>";
$str_result .= "<p>" . $row['address'] . "</p>";
$str_result .= "<p>" . $row['postcode'] . "</p>";
$str_result .= "<p>" . $row['telephone'] . "</p>";
$str_result .= "<p>" . $row['email'] . "</p>";
$str_result .= "<p>" . $row['website'] . "</p>";
}
mysqli_free_result($result);
}else{
$str_result = "<h2>No salon selected</h2>";
}
}
echo $str_result;
?>
<?php
if(trim($_POST['submit']) == "Submit comment"){
//Get any submitted comments and insert
$comment = clean_string($db_server, $_POST['comment']);
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name = "") $error .= "<p class='error'>You must upload an image!</p>";
$originalname=$_FILES['photo']['name'];
$type=$_FILES['photo']['type'];
if ($type=="image/jpeg") $type=".jpeg"; //if true change
else if ($type=="image/jpg") $type=".jpg";// if not true check this one
else if ($type=="image/png") $type=".png";
$name=uniqid() . $type;
$path="images/" . $name;
$tempname=$_FILES['photo']['tmp_name'];
$size=$_FILES['photo']['size'];
//Error checking
if ($size >1000000) $error .= "<p class='error'>Your image file is to big, it have to be less than 200 mb</p>";
if ($error=="") {
if (move_uploaded_file($tempname, $path)){
$uploadquery="INSERT INTO comments (comment, imagename, salonID, userID) VALUES ('$comment', '$path', $salonid, ". $_SESSION['userID'].")";
mysqli_query($db_server,$uploadquery) or die ("Insert failed " . mysqli_error($db_server) . " " . $uploadquery);
$message= "<h2>Thanks for your comment!</h2><p>Your upload was succesful</p>";
}
}
}
}
//Print out existing comment
$query = "SELECT * FROM comments JOIN users ON comments.userID = users.ID WHERE salonID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)){
$str_comments .="<h2>" . $row['Username'] ."</h2>";
$str_comments .= "<p>" . $row['comment'] . "</p>";
$str_comments .="<img src='" . $row['imagename'] ."' />";
}
mysqli_free_result($result);
?>
<div id="form">
<table><form id='review' action='salonpage.php?salonid=<?php echo $salonid; ?>' method='post' enctype='multipart/form-data'>
<th><h2> Do you want to review the service you recieved?</h2></th>
<tr><td><textarea name="comment" rows="6" cols="40">Write something here!</textarea></td></tr>
<tr><td><input type='file' name='photo' accept='image/jpg, image/jpeg, image/png'/></td></tr>
<br/>
<tr><td><input type='submit' id='submit' name='submit' value='Submit comment' /></td></tr>
</form></table>
<?php echo $message;
echo $str_comments; ?>
</div>
<?php mysqli_close($db_server); ?>
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name = "") $error .= "<p class='error'>You must upload an image!</p>";
$originalname=$_FILES['photo']['name'];
in this code you are using
$name = ""
which is an assignment operator you need to use comparison operator within if condition either ==or ===
I think, you are talking about $error, if i am correct then you did not echo $error variable in your above mention code. One more thing add else part on if block "if ($comment != '')" else {$error.="no comment entered" }

Categories