I have an application that where users can post announcements and comment on posts. My problem is that whenever a comment is posted, It shows up on every announcement post. How can I post comments so that they show up on that specific post?
I have 2 database tables: "announcement: id, name, announcementTitle, announcement, image" and "comment: id, post_id, name, comment" with foreign key attached to comment.
Here is my home.php where the announcements and comments are echoed
<div class="container">
<div class="mx-auto">
<?php
if (isset($_SESSION['username'])) {
echo'
<h1 style="text-decoration:underline">Post an announcement</h1>
<form method="post" action="announcement.php" enctype="multipart/form-data">
<input type="text" name="announcementTitle" placeholder="Enter Subject"><br>
<textarea name="announcementBox" rows="5" cols="40" placeholder="Enter Announcement"></textarea><br>
<input type="file" name="image" accept="image/jpeg">
<button name="announcement">Submit</button>
</form>';
}
$query = "SELECT * FROM announcement ORDER BY id DESC";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="row" style="color:black;background-color:white;border-radius:5px;padding:10px;margin-top:10px;margin-bottom:70px">';
echo '<div class="column" style="width:100%;border:5px">';
if (isset($_SESSION['username'])) {
echo '<form method="post" action="announcement.php">';
echo "Posted by " .$row["name"]. " click X to delete:";
echo '<input type="hidden" name="postID" value="'.$row['id'].'">';
echo '<button name="delete" style="float:right">X</button>';
echo '</form>';
}
echo $row['announcementTitle'].'<br>';
echo $row['announcement'].'<br>';
echo '<img width="20%" src="data:image;base64,'.$row['image'].'"alt="Image" style="padding-top:10px">';
echo'
<form method="post" action="comment.php">
<textarea name="commentbox" rows="2" cols="50" placeholder="Leave a Comment"></textarea><br>
<button name="comment">Submit</button>
</form>';
echo "Comments:<p><p>";
echo " <p>";
$find_comment = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($con,$find_comment);
while ($row = mysqli_fetch_array($res)) {
echo '<input type="hidden" name="postID" value="'.$row['post_id'].'">';
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name: $comment<p>";
}
if(isset($_GET['error'])) {
echo "<p>100 Character Limit";
}
echo '</div></div>';
}
?>
</div>
</div>
Here is comment.php where comments are put in the database
<?php
session_start();
$con = mysqli_connect('localhost', 'root', 'Arv5n321');
mysqli_select_db($con, 'userregistration');
$namee = '';
$comment = '';
$comment_length = strlen($comment);
if($comment_length > 100) {
header("location: home.php?error=1");
}else {
$que = "SELECT * FROM announcement";
$res = mysqli_query($con,$que);
while ($row = mysqli_fetch_array($res)) {
$post_id = $row['id'];
}
$namee = $_SESSION['username'];
$comment = $_POST['commentbox'];
$query = "INSERT INTO comment(post_id,name,comment) VALUES('$post_id','$namee','$comment')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
?>
Here is announcement.php where announcements are put in the database
<?php
session_start();
//$con = mysqli_connect('freedb.tech', 'freedbtech_arvindra', 'Arv5n321', 'freedbtech_remote') or die(mysqli_error($con));
$con = mysqli_connect('localhost', 'root', 'Arv5n321', 'userregistration') or die(mysqli_error($con));
if (isset($_POST['announcement'])) {
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
date_default_timezone_set("America/New_York");
$title = $_POST['announcementTitle']." (<b>".date("m/d/Y")." ".date("h:i:sa")."</b>)";
$paragraph = $_POST['announcementBox'];
if (empty($paragraph)||empty($title)) {
header('location:home.php?error=fillintheblanks');
}else{
$nam = $_SESSION['username'];
$query = "insert into announcement(name,announcementTitle,announcement,image) values('$nam','$title','$paragraph','$image')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
}else if (isset($_POST['delete'])){
$query = "delete from announcement where id='".$_POST['postID']."';";
$result = mysqli_query($con,$query);
if ($result) {
header('location:home.php?success=deleted');
} else {
header('location:home.php?error=couldnotdelete');
}
}
else {
header('location:home.php');
}
I am a little new to PHP so any help is good.
Related
Hope You all have a Great Day, I new with SQLITE DB and so I'm little confused about handling BLOB data.I tried lot of things ,but nothing get in to favor of me.
Here is My Code
INSERTING DATA
insert.php
<form method="POST" enctype="multipart/form-data">
model no:<input type="text" name="model_no"\><span style="color: red"><?php echo $messages["model_no"]; ?></span>
image:<input type="file" name="image" id="image"\><span style="color: red">
<input type="submit" value="save" id="save" name="save"/>
<input type="reset" value="Clear"/>
</form>
include.php
<?php
$flag = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
//checking save button is clicked
if(isset($_POST["save"])){
$model_no = $_POST['model_no'];
$image = $_FILES['image']['name'];
if($model_no != '' && $image != ''){
$flag = 1;
}
if($flag == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
//echo $sql;
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
//echo $numRows;
if($numRows != 0){
$flag = 0;
echo "error:this model no is already taken";
}else{
$sqlp = "INSERT INTO fisfis(model_no, image) values('$model_no','$image')";
if($dbb->exec($sqlp)){
echo "data inserted successfully\n";
}
else{
echo"error:\n";
echo "data not inserted \n";
echo"contact admin for details\n";
}
}
}
}
else{
echo"error:\n";
echo "data not inserted : data fields cannot be empty\n";
}
}
?>
this is very successfully inserting data in to my table (table name:fisfis)
DISPLAYING DATA
display.php
<form method="POST" enctype="multipart/form-data">
<p>Enter Barcode : <input type="text" name="search_model" id="search_model" /></p>
<!--<p><img src='image.php?id=<?php //echo $row['model_no'];?>'/></p>-->
<p><input type="submit" value="search" name="search" id="search"/></p>
</form>
display_include.php
<?php
$flag2 = 0;
$flag3 = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
$db = new MyDB();
if(isset($_POST["search"])){
$model_no = '';
$model_no = $_POST['search_model'];
if($model_no != ''){
$flag2 = 1;
}
if($flag2 == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
echo $numRows;
if($numRows == 0){
echo 'sorry this model no is not exists';
echo '<br/>';
echo 'create new';
$flag2 = 1;
}else{
echo "this is exisists";
$flag3 = 1;
}
if($flag3 == 1){
$sqla = 'SELECT * FROM fisfis WHERE model_no = "'.$model_no.'"';
$result = $dbb->query($sqla);
while($row = $result->fetchArray(SQLITE3_ASSOC) ) {
echo "MODEL NO = ". $row['model_no'] ."\n";
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
echo $img;
}
}
}
}
}
?>
the display part displaying all data other than blob ,what i have tried
1.try to echo the image inside the php script
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
try to display image inside html tag
but this is not working,please help me to fix this,thanks in advance
My explaining is not good, so here is a show-and-tell. I made a repro so I wouldn't forget any necessary bits.
The database table is defined:
CREATE TABLE `imgrepro` (
`id` INTEGER NOT NULL,
`photo` BLOB,
PRIMARY KEY(`id`)
);
It is seeded with one row, id = 1, photo is NULL.
The POST block will insert the image into the BLOB column in the db. The rest of the script will fetch the image and the html will display it.
<?php
$db = new SQLite3("***********\stacktest.db");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// insert photo
$photo = file_get_contents($_FILES['fname']['tmp_name']);
$query = $db->prepare("UPDATE imgrepro set photo = :photo where id = 1");
$query->bindValue(':photo',$photo,SQLITE3_BLOB);
$result = $query->execute();
}
// get photo if there is one
$rows = $db->query("SELECT * from imgrepro")->fetchArray(SQLITE3_ASSOC);
$showphoto="";
if (count($rows) > 0) {
$showphoto=base64_encode($rows['photo']);
}
$db->close();
?>
<!DOCTYPE html>
<head>
<title>Say Cheese!</title>
</head>
<!-- show the photo -->
<img alt="no photo yet" src="data:image/jpeg;base64,<?= $showphoto ?>" >
<form action="imgrepro.php" method="post" enctype="multipart/form-data">
<input type="file" name="fname" accept=".jpg">
<input type="submit">
</form>
I don't really know how to explain my question, but I am in need. Of how to display warning before update into database.
example:
<?php
#Get id and yes before update waring code
if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo "retry";
}
exit();
}
$id = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
here is my full code where I am trying to display the warning before updating into database
<?php
include_once 'init.php';
$error = false;
// check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if (preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if (isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username = $_SESSION["user_name"];
$result = mysqli_query($conn, "select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$idd = $row["id"];
$username = $row["username"];
$id = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"];
$qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
if ($show < $balance) {
echo "you cant buy here";
exit();
} elseif ($show > $balance) {
$redut = $balance - $show;
#display the warning before updating into daase if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo mysql_error();
}
exit();
}
$idd = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table><input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div></table>
I don't really know where am wrong with the code, but the expected warning before update do not display and the database is not updated. big thanks in advance.
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
change this to
if (isset($_GET["yes"]) && $_GET["yes"] == 'true') {
servers take the GET method as a string. not boolean
I don't really get what kind of warning you are trying to display. If it is for a user you can use the print or echo function. It is possible to echo a block of html so:
echo '<div class=”warning-msg”><p>MY WARNING</p></div>'
will display the block. Only thing is the warning may not be in de correct place or time.
Or in js
echo ‘<script type="text/javascript">’
echo ‘alert(“message successfully sent”)’
echo ’</script>’
If the waring is for jou personal use the build in php error handeling handeling.
Here is a snippet for a query function using php.
Use:
$query = query("SELECT ... (SQL)", $variable);
I have a form with uploading multiple files.
When I upload let's say two images and when I click submit, the images are displayed properly, but when I edit some other input and click submit button, the images are gone.
Here's my code:
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$id = $row->id;
$title = $row->title;
$body = $row->body;
$status = $row->status;
}
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$body = $_POST['body'];
$image = $_POST['image'];
$status = $_POST['status'];
//if($_FILES['image']['tmp_name']) {
if(!empty($_FILES['image']['name'])) { //Edit
// delete old image
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$old = $row->filename;
unlink('../uploads/' . $old);
}
$query = "DELETE FROM postimage WHERE post_id = $id";
$delete_images = $db->query($query);
foreach($_FILES['image']['tmp_name'] as $key => $tmp_name) {
$filename = rand(100,999)."-".$_FILES['image']['name'][$key];
$filetmp = $_FILES['image']['tmp_name'][$key];
if(move_uploaded_file($filetmp, '../uploads/' . $filename)) {
$query = "INSERT INTO postimage(post_id, filename) ";
$query .= "VALUES($id, '$filename')";
$insert_images = $db->query($query);
}
}
}
$query = "UPDATE posts SET ";
$query .= "title = '$title', ";
$query .= "body = '$body', ";
$query .= "status = '$status', ";
$query .= "updated = now() ";
$query .= "WHERE id = $id ";
$update_post = $db->query($query);
//header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title">Post title</label>
<input type="text" value="<?php echo $title; ?>" name="title">
</div>
<div class="form-item">
<label for="body">Post body</label>
<textarea id="editor" name="body" rows="10" cols="30"><?php echo $body; ?></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<?php
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$filename = $row->filename;
echo '<img width="100" height="70" src="../uploads/' . $filename . '">';
}
?>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="<?php echo $status; ?>"><?php echo $status; ?></option>
<?php
if($status == 'published') {
echo '<option value="draft">draft</option>';
} else {
echo '<option value="published">published</option>';
}
?>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Update post">
</div>
</form>
When I'm using simple form with uploading a single image and connects with only one table, I usually fix that problem with this:
if(empty($image)) {
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$image = $row->image;
}
}
How can I solve this problem using multiple upload input?
EDITED: change it to
if(!empty($_FILES['image']['name']))
because $_FILES['image']['tmp_name'] always return path to temp so jou cannot test it for empty
I've solved the problem.
When using multiple file upload, the if statement has to be changed, so in this case it should be: if(!empty($_FILES['image']['tmp_name'][0]))
I try to make online quiz with images questions, and i need your help/advice.
My images is stored on database where have an id "image". My upload works fine, image is stored on database...but i can't show image in questions.
Here is my structure from database: http://imageshack.com/a/img923/8746/Kf16xl.jpg
And that's my code from show questions with image:
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysqli_query($connection, "SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="submit" value="Finish">
</form>';
exit();
}
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
$singleSQL = mysqli_query($connection, "SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection, "SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
The part with show images is:
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
Thank you very much for allocating your time!
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