making multiple choice with data from database - javascript

I want to make a multiple choice and the question is coming from database. I am sure that my database name is correct, but when i click next, the question is not changing, it is directly going to the end/result of question and the question is not random too. The last question that I inserted into the database is displayed in webpage. Please help
this is my code:
<?php
require_once('includes/db_conn.php');
$query = "select * from question";
$query_result = $dbc->query($query);
$num_questions_returned = $query_result->num_rows;
if ($num_questions_returned < 1){
echo "There is no question in the database";
exit();}
$questionsArray = array();
while ($row = $query_result->fetch_assoc()){
$questionsArray[] = $row;
}
$correctAnswerArray = array();
foreach($questionsArray as $question){
$correctAnswerArray[$question['question']] = $question['correct_answer'];
}
$questions = array();
foreach($questionsArray as $question) {
$questions[$question['question']] = $question['question'];
}
$choices = array();
foreach ($questionsArray as $row) {
$choices[$row['question']] = array($row['wrong_answer1'], $row['wrong_answer2'], $row['wrong_answer3'], $row['correct_answer']);
}
error_reporting(0);
$address = "";
$randomizequestions ="yes";
$a = array(
1 => array(
0 => $question['question'],
1 => $row['wrong_answer1'],
2 => $row['wrong_answer2'],
3 => $row['wrong_answer3'],
4 => $row['correct_answer'],
6 => 4
),
);
$max=1;
$question=$_POST["question"] ;
if ($_POST["Randon"]==0){
if($randomizequestions =="yes"){$randval = mt_rand(1,$max);}else{$randval=1;}
$randval2 = $randval;
}else{
$randval=$_POST["Randon"];
$randval2=$_POST["Randon"] + $question;
if ($randval2>$max){
$randval2=$randval2-$max;
}
}
$ok=$_POST["ok"] ;
if ($question==0){
$question=0;
$ok=0;
$percentage=0;
}else{
$percentage= Round(100*$ok / $question);
}
?>
<HTML><HEAD>
<SCRIPT LANGUAGE='JavaScript'>
<!--
function Goahead (number){
if (document.percentaje.response.value==0){
if (number==<?php print $a[$randval2][6] ; ?>){
document.percentaje.response.value=1
document.percentaje.question.value++
document.percentaje.ok.value++
}else{
document.percentaje.response.value=1
document.percentaje.question.value++
}
}
if (number==<?php print $a[$randval2][6] ; ?>){
document.question.response.value="Correct"
}else{
document.question.response.value="Incorrect"
}
}
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=FFFFFF>
<CENTER>
<H1><?php print "$title"; ?></H1>
<TABLE BORDER=0 CELLSPACING=5 WIDTH=500>
<?php if ($question<$max){ ?>
<TR><TD ALIGN=RIGHT>
<FORM METHOD=POST NAME="percentaje" ACTION="<?php print $URL; ?>">
<BR>Percentaje of correct responses: <?php print $percentage; ?> %
<BR><input type=submit value="Next >>">
<input type=hidden name=response value=0>
<input type=hidden name=question value=<?php print $question; ?>>
<input type=hidden name=ok value=<?php print $ok; ?>>
<input type=hidden name=Randon value=<?php print $randval; ?>>
<br><?php print $question+1; ?> / <?php print $max; ?>
</FORM>
<HR>
</TD></TR>
<TR><TD>
<FORM METHOD=POST NAME="question" ACTION="">
<?php print "<b>".$a[$randval2][0]."</b>"; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="1" onClick=" Goahead (1);"><?php print $a[$randval2][1] ; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="2" onClick=" Goahead (2);"><?php print $a[$randval2][2] ; ?>
<?php if ($a[$randval2][3]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="3" onClick=" Goahead (3);"><?php print $a[$randval2][3] ; } ?>
<?php if ($a[$randval2][4]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="4" onClick=" Goahead (4);"><?php print $a[$randval2][4] ; } ?>
<BR> <input type=text name=response size=8>
</FORM>
<?php
}else{
?>
<TR><TD ALIGN=Center>
The Quiz has finished
<BR>Percentage of correct responses: <?php print $percentage ; ?> %
<p>Home Page
<?php } ?>
</TD></TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
this is my process add data to database:
<?php
include('includes/header.html');
error_reporting(-1);
ini_set('display_errors', 'On');
//Check for empty fields
if(empty($_POST['question'])||
empty($_POST['correct_answer']) ||
empty($_POST['wrong_answer1']) ||
empty($_POST['wrong_answer2']) ||
empty($_POST['wrong_answer3']))
{
echo "Please complete all fields";
exit();
}
//Create short variables
$question = $_POST['question'];
$correct_answer = ($_POST['correct_answer']);
$wrong_answer1 = ($_POST['wrong_answer1']);
$wrong_answer2 = ($_POST['wrong_answer2']);
$wrong_answer3 = ($_POST['wrong_answer3']);
//connect to the database
require_once('includes/db_conn.php');
//Create the insert query
$query = "INSERT INTO question VALUES ('$question', '$correct_answer', '$wrong_answer1','$wrong_answer2','$wrong_answer3')";
$result = $dbc->query($query);
if($result){
echo "Your quiz has been saved";
} else {
echo '<h1>System Error</h1>';
}
$dbc->close();
?>

Your first mistake is making array of $a why are you not using $choices which you had made in last for loop and for random questions handle $choices array and your submit button of next is outside the form so you will not get form values on next button.take it inside the form tag.
Another thing is on radio button click don't write anything just write your function on submit click event and then handle the next question after saving the previous answer.
These are what my suggestions.. for more help put here your database back up and its connected files so that I can help you in coding.

Related

Change page from Next button with id

I'm doing a program where I have several exercises with their id (e.g. Id = 1, 2, 3 ...) What I would like to do is that once the user is in an exercise, he can press the Next button and take him to the next exercise, for example id + 1.
Below I show what I've done. Can you help me?
This is my modified question, now it works:
<?php
include_once("functions.php");
// Start the session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
/*echo*/ $id=$_GET['id']; // Current question
$sql = "SELECT * FROM exercises where exercise_id='$id'";
$result = $conn->query($sql); /*Check connection*/
$question_ids = [];
$result2 = doSearch($conn, 'exercise_id');
while($row = $result2->fetch_assoc()) {
array_push($question_ids, $row["exercise_id"]);
}
$order = $_GET['order'];
$next_question_id = -1;
$next_question_order = $order + 1;
if (count($question_ids) >= $next_question_order) {
$next_question_id = $question_ids[$order];
}
?>
<div id="centered_B" class="header">
<?php
$row = $result->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"]?>"><br/><br/>
<form action='' method='post'>
<input type="radio" name="choice" value= "1" /><img src="<?php echo $row["image_path_A"] ?>"/><br>
<input type="radio" name="choice" value= "2" /><img src="<?php echo $row["image_path_B"] ?>"><br>
<input type="radio" name="choice" value= "3" /><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p2>Select difficulty level:</p2>
<form action='' method='post'>
<select name="choose" id="choose">>
<option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
<option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
<option value="3" <?php if($row["difficulty"]=="3") { echo "selected"; } ?> >3</option>
<option value="4" <?php if($row["difficulty"]=="4") { echo "selected"; } ?> >4</option>
<option value="5" <?php if($row["difficulty"]=="5") { echo "selected"; } ?> >5</option>
</select>
<br><br><br>
<input class="buttonSubmit" type="submit" name="submit" value="Submit">
<?php
if ($next_question_id >= 0) {
?>
<a href="?id=<?php echo $next_question_id; ?>&order=<?php echo $next_question_order; ?>" class="buttonNext" >Next Question</a>
<?php
}
?>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
$user_id = $_SESSION['user_id'];
$user_check_query = "SELECT * FROM users WHERE id='$user_id'";
if(isset($_POST['choice'], $_POST['choose'])){
$choice_answer=$_POST['choice'];
$difficulty=$_POST['choose'];
// */$user_id = $_SESSION['user_id'];*/
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES ('$id','$user_id', '$difficulty', '$choice_answer')";
$sql=mysqli_query($conn,$query);
}
}
?>
Not sure what your JS or PHP level is, but here's a pure PHP solution - not using JS.
Things to notice:
Using PDO parameterized queries to secure against SQL injection
Using a hidden form field to pass around the current question ID. After the user submits, we insert their response in the DB, and then redirect to the next question by incrementing $id++
You had 2 <form> tags. I removed one.
Please note, this code is not tested. Let me know if you have any questions. Good luck!
<?php
session_start();
// Using PDO instead of mysqli. Nothing wrong with mysqli but I'm more comfortable with PDO.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// This is your connection to the DB.
$pdo = new PDO($dsn, $user, $pass, $opt);
// This is the current question being displayed to the user.
$id = $_GET['id'];
// You should probably do some validation on $id here. Should it be numeric, not null etc.
// Notice that we're using ? instead of passing the value directly to the DB. This is called prepared statements.
// https://phpdelusions.net/pdo#prepared
$stmt = $pdo->query('SELECT * FROM exercises where exercise_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// You should also validate the $row here. Did you actually find a question from the DB?
?>
<div id="centered_B" class="header">
<p><?php echo $row["exercise_id"] . ". " . $row["text"] ?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"] ?>"><br/><br/>
<!-- Changed the method to GET -->
<form action="" method="GET">
<!-- Notice that we're passing the question ID to server when the form submits. -->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<label>
<input type="radio" name="choice" value="1"/>
</label><img src="<?php echo $row["image_path_A"] ?>"/><br>
<label>
<input type="radio" name="choice" value="2"/>
</label><img src="<?php echo $row["image_path_B"] ?>"><br>
<label>
<input type="radio" name="choice" value="3"/>
</label><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p>Select difficulty level:</p>
<label for="choose"> Difficulty
<select name="choose" id="choose">>
<option value="1" <?php if ($row["difficulty"] == "1") {
echo "selected";
} ?> >1
</option>
<option value="2" <?php if ($row["difficulty"] == "2") {
echo "selected";
} ?> >2
</option>
<option value="3" <?php if ($row["difficulty"] == "3") {
echo "selected";
} ?> >3
</option>
<option value="4" <?php if ($row["difficulty"] == "4") {
echo "selected";
} ?> >4
</option>
<option value="5" <?php if ($row["difficulty"] == "5") {
echo "selected";
} ?> >5
</option>
</select>
</label>
<br><br><br><!--- Button --->
<!-- <button class="buttonSubmit" >Submit</button>-->
<input type="submit" name="submit" value="Submit">
<button class="buttonNext">Next Question</button>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
// Changed to a single if-statement
if (isset($_POST['choice'], $_POST['choose'])) {
$user_id = $_SESSION['user_id'];
$choice_answer = $_POST['choice'];
$difficulty = $_POST['choose'];
// Again, using prepared statements.
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES (?, ?, ?, ?)";
$pdo
->prepare($query)
->execute([$id, $user_id, $difficulty, $choice_answer]);
// Redirect to self with incremented question ID.
// https://stackoverflow.com/a/8131377/296555
header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $id++);
die;
}
}
Maybe this can help you:
var i=$_GET['id']){;
function getNext()
{
var = var + 1; //increase var by one
return var;
}</script>
<button class="buttonNext" onclick="getNext" >Next Question</button>
Uhm, I don't know where to start here...
Ok, for first your code is horrible - regarding in style, security and everything - sorry ;)
But to help with your problem:
Don't access the next id directly but go by
SELECT * FROM exercises WHERE exercise_id > $currentId ORDER BY exercise_id ASC LIMIT 0,2
This will help if you want to delete an exercise at some point, so have a gap like 1,2,4 (3 was deleted). You can also create a position field to sort the order of the question manually, but I guess that's too advanced for first.
However:
On start you check if there's a $_GET['id'] param and set this to $currentId. Best by $currentId = (int)$_GET['id'] to prevent a serious injection. If no GET param is there, set $currentId = 0 (first call then).
Then you run the query to get your exercise - it will be in the first row of the result.
On HTML side you just assign the exercise_id from the database result to the link which leads on the next exercise (so no JavaScript is required).
To test, if there's a next question at all check if a second row exists in the result (that's why LIMIT 0,2 instead of 0,1) to decide if to show the "next exercise button".

automatically populate text box based on select entry

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>
Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

How do I filter for similar products using checkboxes with PHP, AJAX and JS?

Here is an image of what I'm trying to accomplish -
Example of my Database Table -
My goal is to get a similar product to the product that is currently displaying without refreshing the page. I am trying to find similar products is by using check boxes.
I first got the id using $_GET['id'] which should be equal to one of the values in my table.
I then used PDO Fetch to get the product name, brand, quanity and price of that particular id and store it as a string.
What I need help with is using JQuery/AJAX to get the checkboxes that are checked and then send the information to a PHP file that would check if filter results match with any data from the table.
How can I do this?
This is my product.php file
<?php
require ('includes/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form>
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
</body>
</html>
I managed to solve this out, glad I didn't give up.
My product.php File
<?php
require ('/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form method="post" action="">
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
<div class="filter_container">
<div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>
<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>
Here is my JS File
$(document).ready(function() {
function showValues() {
var brand;
var quantity;
var calories;
var price;
//Gets product name
var prod_name = $('input[name="prod_name"]').val();
//Gets brand
if($('input[name="brand"]').is(':checked'))
{brand = $('input[name="brand"]').val();} else {brand = ""}
//Gets quantity
if($('input[name="quantity"]').is(':checked'))
{quantity = $('input[name="quantity"]').val();} else {quantity = ""}
//Gets calories
if($('input[name="calories"]').is(':checked'))
{calories = $('input[name="calories"]').val();} else {calories = ""}
//Gets price
if($('input[name="price"]').is(':checked'))
{price = $('input[name="price"]').val();} else {price = ""}
$.ajax({
type: "POST",
url: "/query.php",
data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name},
cache: false,
success: function(data){
$('.filter_container').html(data)
}
});
}
//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );
//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
$(this).removeAttr('checked');
showValues();
});
});
Here is my PHP File
<?php
include('/db.php');
$prod_name = $_POST['prod_name'];
$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];
if(!empty($Cbrand))
{
$data1 = "brand = '$Cbrand' AND";
}else{
$data1 = "";
}
if(!empty($Cquantity))
{
$data2 = "quantity = '$Cquantity' AND";
}else{
$data2 = "";
}
if(!empty($Ccalories))
{
$data3 = "calories = '$Ccalories' AND";
}else{
$data3 = "";
}
if(!empty($Cprice))
{
$data4 = "price = '$Cprice'";
}else{
$data4 = "";
}
$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details
$stringAnd = "AND"; //And
$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string
$endAnd = substr($main_string, -3); //Gets the AND at the end
if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
$main_string = "";
}
else{
$main_string = "WHERE $data1 $data2 $data3 $data4";
}
if($main_string == ""){ //Doesn't show all the products
}else{
$sql = "SELECT COUNT(*) FROM products $main_string";
if ($res = $handler->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
$sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {
if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
//The product currently being displayed is blank when using the filter
}
else{
?>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<div class="form-result">
<td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<?php
}
}
} /* No rows matched -- do something else */
else {
?>
<div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
<?php
}
}
}
$handler = null;
$res = null;
?>

How to differentiate each submit button in a foreach loop

My code:
<?php
require_once 'core/init.php';
if($result = $db->query ("SELECT * from countries")) {
if($count = $result->num_rows) {
$rows = $result->fetch_all(MYSQLI_ASSOC);
}
}
?>
<div class="region">
<h1>Europe</h1>
<ul class="country" style ="list-style-type:none">
<?php foreach ($rows as $key => $row) { ?>
<li>
<a href=""=<?php echo $row['country_id']; ?>">
<a href=""=<?php echo $row['region_id']; ?>">
<?php echo $row['country_name']; ?></a> <br>
<?php
if (isset($_FILES['country_img']) === true) {
if (empty($_FILES['country_img']['name']) === true) {
echo 'please choose a file!';
print_r ($_POST);
} else {
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['country_img']['name'];
$file_extn = end(explode('.', $file_name));
$file_temp = $_FILES['country_img']['tmp_name'];
if (in_array($file_extn, $allowed) ===true) {
if ($_POST['id'] = $_POST['id']) {
addcountryimage($row['country_id'], $file_temp, $file_extn);
}
header ('Location: tes2.php');
break;
}else {
echo 'Incorrect file type. Allowed: ';
echo implode (', ', $allowed);
}
}
}
if (empty($row['country_img'] === false)) {
echo '<img src="', $row['country_img'], '" alt="', $row['country_name'], '\'s Image">';
}
?>
<p> <?php echo $row['country_bio']; ?></p>
<?php
global $session_user_id;
if (is_admin($session_user_id) === true) { ?>
<form action="" method="POST" name="" enctype="multipart/form-data">
<input type="hidden" name="id" id="hidden_id">
<input type="file" name="country_img"> <input type="submit" onclick="document.getElementById('hidden_id').value=$row['country_id']" />
</form>
<?php } ?>
<p> Tour to <?php echo $row['country_name']; ?></p>
</li>
<?php } ?>
</ul>
<h3> More European Country </h3>
</div>
Everything above works, except the fact that it can't differentiate between each submit button. For example, when I update the image on the 5th forms it will always update the 1st form. How can I do this?
The origin of your issue is using multiple id attributes with the same value in your JavaScript events, this is regarded wrong, every element id must be unique, beside this, onclick event with submit typed inputs of form is not working properly.
Add an incremental counter to your loop and then use to distinguish each form hidden element id.
<?php $i = 0;?>
<?php foreach ($rows as $key => $row) { ?>
....
<input type="hidden" name="id" id="hidden_id_<?php echo $i;?>">
....
<input type="submit" onclick="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']" />
<?php
$i++;
} ?>
Another note, I think that onclick event does not works fine with submit type inputs, so I suggest to replace it with onsubmit event in the form itself as:
<form action="" method="POST" name="" enctype="multipart/form-data" onsubmit="document.getElementById('hidden_id_<?php echo $i;?>').value=$row['country_id']">

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

Categories

Resources