I have set a counter in php code to increment the id value in mysql on every next click but when I refresh or reload the page the value is increasing automatically is there any solution for this problem or any other substitute.
<?php
$db = mysqli_connect('localhost','root','root','rahul');
$questions ="";
$msg2 ="";
$o1 ="" ;
$o2 ="" ;
$o3 ="" ;
$o4 ="" ;
$disable = "";
$disable2 = "";
session_start();
if(empty($_SESSION['count']))
$_SESSION['count'] = 0;
if(isset($_POST['sub1'])){
$ans = $_POST['ans'];
$email = "rahul#gmail.com";
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = $order ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1)
{
$disable2 = "disabled";
}
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
/*
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
*/
echo $ans. $email;
}
$sql4 = mysqli_query("select * from result");
$row = mysqli_fetch_array($db, $sql4);
// while()
echo $row['id'];
for($i=1;$i<=5;$i++)
{
}
?>
<?php
if(isset($_POST['sub2'])){
$result2 = $_SESSION['count']-1;
$_SESSION['count'] = $result2;
$sql = (" SELECT * FROM qna WHERE id = $result2 ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
}
session_write_close();
?>
<?php
if(isset($_POST['start'])){
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = 1 ");
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>=5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
session_write_close();
}
?>
<center><br><br><br>
<form method="post">
<input type="submit" name="start" value="start">
</form>
Log out
<form action="" method="post" >
<table border="1" height="300px" width="500px">
<tr>
<th colspan="2"><?php echo $questions; ?></th>
</tr>
<tr>
<td><input type="radio" name="ans" id="ans" value="<?php echo $o1; ?>"><?php echo $o1; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o2; ?>"><?php echo $o2; ?></td>
</tr>
<tr>
<td><input type="radio" name="ans" value="<?php echo $o3; ?>"><?php echo $o3; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o4; ?>"><?php echo $o4; ?></td>
</tr>
<tr colspan="2">
<td><center><input type="submit" name="sub1" value="next" <?php echo $disable ?>> </td>
<td><center><input type="submit" name="sub2" value="previous" <?php echo $disable2 ?>>
<input type="submit" name="submit3" value="submit" > </td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit3']))
{
$ans = $_POST['ans'];
$email = "dummy";
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
echo $ans. $email;
}
?>
when you are reloading a web-page, you are reloading its POST (and also GET) data as well if it's there. if you are submitting a form then the target page contains POST data in its header. so if you reload this page it's like you would have clicked the button again.
since you are already using a session there is a workaround:
add a hidden field with a micro-timestamp in your form. this micro-timestamp will be different every time your page gets loaded (per user) - but this "new" timestamp only get's posted when you use the button. when you just refresh the page, you are reloading with the old timestamp.
so you just need to save compare the last timestamp (saved in a session variable) with the currently posted timestamp. if they are equal - the page just got refreshed - if they are not equal, then you got a new timestamp which was sent by your form:
<?php
session_start();
if(!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
if(!isset($_POST["timestamp"]))
$_POST["timestamp"] = 0;
// previous timestamp - saved in session variable:
$prev_ts = $_SESSION["timestamp"];
// currently posted timestamp:
$post_ts = $_POST["timestamp"];
if($prev_ts != $post_ts)
{
// code to increase your counter goes here.
$feedback = "button pressed";
}
else
{
// do nothing when the page just got refreshed
$feedback = "refreshed";
}
$_SESSION["timestamp"] = $post_ts;
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php echo $feedback; ?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<input type="hidden" name="timestamp" value="<?php echo microtime(); ?>">
<input type="submit" name="go" value="count">
</form>
</body>
</html>
Related
I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...
I am passing the level of the question through query string to the page. Next, I am prompting user to give the answer from the option. Now, if the answer is correct, score is incremented. Now the issue is that if the answer is wrong, I am not getting any thing in browser.
<?php
session_start();
if ( isset($_POST['submit']))
{
$qid = $_POST['qid'];
$answer = $_POST['answer'];
// $range= $_POST['range'] ;
$dbc = mysqli_connect('localhost','root','1234','islamic')
or die('unable to connect');
$query = "select * from question where qid = '$qid' ";
$result = mysqli_query($dbc,$query);
$row = mysqli_fetch_array($result);
if ( $answer == $row['answer'])
{
// echo 'Congrats, Your answer is correct.'.$_COOKIE['username'];
#$score = ++$_COOKIE['score'];
setcookie('score',$score);
}
#$page = ++$_COOKIE['page'];
if ( #$page == 4)
{
echo 'score is '.$_COOKIE['score'];
setcookie('score',0);
setcookie('page',0);
echo 'Go to Home ';
exit();
}
setcookie('page',$page);
}
if ( isset($_GET['level']))
{
$_SESSION['level'] = $_GET['level'];
}
$level = $_SESSION['level'];
$dbc = mysqli_connect('localhost','root','1234','islamic')
or die('unable to connect');
// $query = "Select * from question";
// $result = mysqli_query($dbc,$query);
// $num_rows = mysqli_num_rows($result);
$range = rand(0,6);
$query = "select * from question where level = '$level' limit $range,1";
$result = mysqli_query($dbc,$query);
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['A']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['B']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['C']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['D']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
}
mysqli_close($dbc);
?>
You script doesn't display anything if the database query returns no results.
Get rid of the while and simply use $row = mysqli_fetch_array($result);
I am making a web-application for Quiz competition. For the purpose, I wrote a php script which is processed by the same page. Now when I am adding scores and question numbers, the score is incremented or remain unchanged depending upon the previous answer if someone is refreshing the page. Now I googled the problem and found something like PRG.But this method works if the page is processed by other page (What I think ). Again, a friend of mine told me to use Javascript. But what if someone has turned Js off? Can't we have a solution in php itself. I tried session method also, but I did not fix the issue .
Please help me .
PHP Quiz script is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
Edit:
I changed my code as Mat is suggested. But it is not allowing me to have different question from the table?
The revised php code is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$is_new_post = true;
if (isset($_SESSION["myform_key"]) && isset($_POST["myform_key"]))
{
if($_POST["myform_key"] == $_SESSION["myform_key"] ){
$is_new_post = false;
}
}
if($is_new_post){
$_SESSION["myform_key"] = $_POST["myform_key"];
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="hidden" name="myform_key" value="<?php echo md5("CrazyFrogBros"); ?>" />
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
I tried session method also, but I did not fix the issue
I don't know how you code it but you can try this:
1. Set a session token with unique hash value e.g.
$_SESSION['formtoken'] = sha1(uniqid('', true));
include it in your form (input hidden) value = $_SESSION['formtoken']
everytime the user submit the form reset the $_SESSION['formtoken'] value
I have file category.php where i have:
Category name / Moderator
Economy / uername1
Math / username2
Biology / username1
Every category i can update and add new category with username who can moderate some category.
I have problem with categorie.php because when i click update on label Category name in input write me Economy and username1 when i click on update some other category like Math in input writes me again Economy and username1.
Second problem i have is when i want to add a new category with moderator. After i click submit doesn't insert in my mysql database name of added category with moderator.
<?PHP
session_start();
if(!isset($_SESSION["type_id"])){
header("Location:index.php");
exit();
}
else if($_SESSION["type_id"]!=0)
{
header("Location:index.php");
exit();
}
include_once("meni.php"); ?>
<div class="mid-right"><?php
$dbc=mysql_connect("localhost","2013","013");
if (!$dbc)
{
echo 'Error!'.mysql_error();
exit();}
$db=mysql_select_db("2013_db",$dbc);
$category = $category_id = $name = $user_id = "";
$id = 0;
if(isset($_POST['username'])) {
if (isset($_POST['type_id'])) {
$type_id = $_POST['type_id'];
} else {
$type_id = 2;
}
$id = $_POST['new'];
if ($id == 0) {
$name = $_POST['name'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$sql = "INSERT INTO category (category_id, name, user_id) VALUES ($category_id, '$name', '$user_id');";
}
$result=mysql_query($sql);
mysql_close($db);
header("Location: category.php");
}
if(isset($_POST['category_id']) && isset($_POST['name']) && isset($_POST['moderator']) && $_SESSION['type_id'] == 0) {
$name = $_POST['name'];
$user_id = $_POST['moderator'];
$category_id = $_POST['category_id'];
$sql = "UPDATE category SET name = '$name', user_id = $user_id WHERE category_id = $category_id";
$result=mysql_query($sql);
mysql_close($db);
header("Location: category.php");
}
if(isset($_GET['categories'])) {
$kategorija_id = $_GET['categories'];
if ($id==2) {
$id = $_SESSION["category_id"];
}
$dbc=mysql_connect("localhost","2013","2013");
if (!$dbc)
{
echo 'Error!'.mysql_error();
exit();}
$db=mysql_select_db("2013_db",$dbc);
$sql = "SELECT k.category_id, k.name, ko.username FROM category k, user ko WHERE k.user_id = ko.user_id AND ko.type_id = 1";
$result=mysql_query($sql);
list($category_id, $name, $user_id) = mysql_fetch_array($result);
} else {
$name = "";
}
?>
<form method="POST" action="categorie.php">
<div>
<input type="hidden" name="category_id" value="<?php echo $category_id ?>"/>
<input type="hidden" name="new" value="<?php echo $id?>"/>
<table>
<tr>
<td><label for="name">Category name:</label></td>
<td><input type="text" name="name" id="name" value="<?php echo $name ?>"/></td>
</tr>
<tr>
<td><label for="moderator">Moderator:</label></td>
<td><select name="moderator">
<?php
$sql2 = "SELECT user_id, username FROM user WHERE type_id = 1 ";
$rs2 = mysql_query($sql2);
while(list($user_id, $username) = mysql_fetch_array($rs2)){
?>
<option value="<?php echo $user_id ?>"><?php echo $username ?></option><?php } ?>
</select></td>
<tr>
<tr>
<td colspan="2"><input type="submit" value="Send" id="submit"/></td>
</tr>
</table>
</div>
</form>
<?php
mysql_close($dbc);
?>
</div>
</div><?php include("footer.php"); ?>
</body>
</html>
I need help about this, I have a PHP page, which searches for records, based on their first and last names, if sql finds the data then the second form comes out, which has lots of textboxes, to update the 'searched'information. And when I click the submit button of the second form , it does nothing, and even if I have syntax or whatever errors I have put on condition if(isset($_POST['submit'])), they end up being disregarded (no error messages will come up), after clicking the submit button, it just goes back to the page's original state, when it has to update the record I have searched for that was just edited. What exactly is the mistake on this part?
class.php - .php file that contains the operations for sql
<? php
$months = array('January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December');
class EmployeeProfile {
public
function openConnection() {
$conn = mysqli_connect("localhost", "root", "", "db_employee");
if (mysqli_connect_errno()) {
echo "Failed to connect to database server";
}
return $conn;
}
public
function insert($query) {
if (mysqli_query($this - > openConnection(), $query) == 1) {
echo "Profile successfully registered!";
} else {
echo "Register failed";
}
}
public
function display($query) {
$result = mysqli_query($this - > openConnection(), $query);
echo "<br><br>";
if ($result - > num_rows == 1) {
while ($row = $result - > fetch_assoc()) {
echo "<table>";
echo "<tr><td><b>First Name</b>: ".$row["firstname"]."</td></tr>";
echo "<tr><td><b>Middle Name</b>: ".$row["middlename"]."</td></tr>";
echo "<tr><td><b>Last Name: </b>".$row["lastname"]."</td></tr>";
echo "<tr><td><b>Date of Birth: </b>".$row["dateofbirth"]."</td></tr>";
echo "<tr><td><b>Age: </b>".$row["age"]."</td></tr>";
echo "<tr><td><b>School: </b>".$row["school"]."</td></tr>";
echo "<tr><td><b>Highest Educational Attainment: </b>".$row["educ"]."</td></tr>";
echo "<tr><td><b>Year Last Attended: </b>".$row["yearattended"]."</td></tr>";
echo "<tr><td><b>Skills: </b>".$row["skills"]."</td></tr>";
echo "<tr><td><b>Previous Company: </b>".$row["prevcompany"]."</td></tr>";
echo "<tr><td><b>Position: </b>".$row["position"]."</td></tr>";
echo "<tr><td><b>Date of Employment:</b> ".$row["dateofemployment"]."</td></tr>";
echo "</table>";
}
} else
{
echo "Profile not found";
}
}
public
function edit($query) {
$result = mysqli_query($this - > openConnection(), $query);
}
}
?>
edit.php - the page itself.
<html>
<title> Edit Profile</title>
<body>
<form method="post" action="?" name="searchform">
<center>
<table>
<tr><td>Enter first or last name</td><td><input type = "text" name="search"><td><td><input type = "submit" value="Search" name="search2"></td></tr>
</form>
</table>
<?php
include("class.php");
if(isset($_POST['search2'])):
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
$emp = new EmployeeProfile();
$emp->openConnection();
$result = mysqli_query($emp->openConnection(), $query);
if($result->num_rows == 1):
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</form>
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "Profile not found";
endif;
endif;
?>
</table>
</center>
</body>
</html>
and I do really think that this line and beyond gets ignored.
This is part of the edit.php file that is shown above.
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
In general, there are two kinds of errors present.
HTML tag order errors, which are extensive
Syntax errors.
- > must be -> to be properly parsed
<? php must be <?php to be properly parsed
The syntax errors are present in both files.
Note: the following code contains some debug statements.
<html>
<head>
<?php
echo "<p>In myquery.php header </p>";
error_reporting(E_ALL);
//echo "<p>" . var_dump($_POST); . "</p>";
//echo "<p>" . var_dump($_GET); . "</p>";
?>
<?php
include("class.php");
?>
<title> Edit Profile</title>
</head>
<body>
<?php
echo "<p>In myquery.php body</p>";
?>
<form method="post" action="?" name="searchform">
<table>
<tr>
<td>Enter first or last name</td>
<td><input type = "text" name="search"><td>
<td><input type = "submit" value="Search" name="search2"></td>
</tr>
</table>
</form>
<?php
echo "<p>about to check _post for search2</p>";
if(isset($_POST['search2'])):
echo "<p>found _post for search2</p>";
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
echo "<p>about to open DB</p>";
$emp = new EmployeeProfile();
$emp->openConnection();
echo "<p>about to place find query</p>";
$result = mysqli_query($emp->openConnection(), $query);
echo "<p>about to check for successful query</p>";
if($result->num_rows == 1):
echo "<p>successful search query</p>";
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</table>
</form>
<?php
echo "<p>about to check for submit second form</p>";
if(isset($_POST['submit'])):
echo "<p>found submit for second form</p>";
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 =
"UPDATE employee
SET firstname='$firstname',
middlename='$middlename',
lastname='$lastname',
dateofbirth='$dateofbirth',
age='$age',
school='$school',
educ='$educ',
yearattended='$yearattended',
skills='$skills',
prevcompany='$prevcompany',
position='$position',
dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
echo "<p>about to update DB</p>";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "<p>search query failed</p>";
echo "Profile not found";
endif;
endif;
?>
</body>
</html>