Foreach loop echoing only one row from database - javascript

This is what my code does: when a username is typed in the #type input field, and if that typed value matches a row value from my database table users, then my jquery code will come to action. My jquery code will then reveal the hidden div that contains text of that typed in username. My problem is my current code ignores other typed in usernames, and for some reason will reveal only one username. Example of my issue:
allen <-- "allen" is typed in input field
--------
[allen] <-- hidden div for allen now shows
pete
-------- <-- "pete" is typed in input field
<-- but hidden div for pete does not show. Why?
Is this an event bubbling issue with my js code? Because I did add e.propagation but it didn't do anything. How would I rewrite my current code so that any username that is typed will reveal a hidden div for it. Because currently I'm only able to get a hidden div for "allen" but not for the rest of the usernames. Please help, here is my code:
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var userid = '<?php echo $userid; ?>';
if (this.value == $("#username"+userid).attr('value')) {
$("#border"+userid).css("display", "block");
}
else {
$("#border"+userid).css("display", "none");
}
});
Sql code:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$userids[] = $row['userid'];
$usernames[] = $row['username'];
}
$stmt->close();
#MohammadBagheri - Output for code below:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo '<pre>'.print_r($row, 1).'</pre>';
}
$stmt->close();
Output:
Array
(
[userid] => 35
[username] => pete
)
Array
(
[userid] => 44
[username] => allen
)

I know what the problem is.
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var username = $(this).val();
var userid = $("input[value='"+username+"']").attr("id");
$("div[id^=border]").css("display", "none");
$("#border"+userid).css("display", "block");
});
You have been selecting the userid of the last occurrence of the loop and set that in jquery code which means it will always show the user with that user id and not checking what you input.
Please let me know if you need more help.

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".

Passing Hidden ID value to another page using javascript php

I am trying to pass hidden value from page to another page and it work fine only for first record however for other records it's showing error
Here is the code:
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_id" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead">
<?php echo $row["jdes"] ?>
</p>
<button type="button" id="requestthis" class="btn btn-primary">
Request
</button>
<?php
}
} else {
echo "Nothing to display Yet";
}
?>
jobs-inner.php
<?php
echo $_GET['hidden_id'];
?>
Javascript:-
$(function() { //ready function
$('#requestthis').on('click', function(e){ //click event
e.preventDefault();
var hidden_id = $('#hidden_user_id').val();
var url = "jobs-inner.php?hidden_id="+hidden_id;
window.location.replace(url);
})
})
Error:-
Undefined index: hidden_id in C:\wamp64\www\project\jobs-inner.php on line 3
It might be a simple problem but I am a beginner and I can't figure it out.
Your value is unique but the id isn't. Make the id of the input unique something like below.
<input type="hidden" id="hidden_user_<?php echo $row["id"] ?>" value="<?php echo $row["id"] ?>">
but you would have to do a count on code below to make it display base on how many rows you have.
<?php
echo $_GET['hidden_id'];
?>
Without JavaScript
$sql = "SELECT id,jdes,title FROM job";
$result = $conn->query($sql);
$count = 1;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<input type="hidden" id="hidden_user_<?php echo $count ?>" value="<?php echo $row["id"] ?>">
<h3><?php echo $row["title"] ?>:</h3>
<p class="lead"><?php echo $row["jdes"] ?></p>
<form id="<?php echo $count ?>" action="jobs-inner.php?hidden_id=<?php echo $row["id"] ?>" method="post">
<input type="submit" vaule="Request">
</form>
<?php
$count++;
}
} else {
echo "Nothing to display Yet";
}
?>

Getting the selected value from a select tag

I am trying to get the value of the selected option from my select. And I am trying to see it's output through a javascript echo. Here's what I've got so far. I am not getting the value
<form method="post" action="">
<select class="form-control" name="empSel" id="empSel">
<?php
$sql2 = "SELECT * FROM employee";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row2 = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row2['lastname'] ?>"><?=
/*$row2['user_surname']." ".*/
$row2['id']."-".$row2['lastname'] ?></option>
<?php
}
?>
</select>
<Label> Confirm</Label>
<div class="form-group col-md-6">
<input type="submit" class="btn btn-block btn-info"
name="submit"/>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$userid = $_POST['empSel'];
echo '<script type="text/javascript"> alert('.$userid.')</script>';
$userid = preg_replace('/\D/', '', $userid);
$sql2 = "SELECT * FROM employee where id ='userid'";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row = mysql_fetch_assoc($result)) {
echo '<script type="text/javascript"> alert("")</script>';
}
}
?>
An javascript alert doesn't pop out on this code. However, when I switch the value in the echo to a different variable an alert pops up. What does it mean? Do I properly get the value of my select and the page refreshed instantly that I didn't get to see it? Thanks
Edit:
An example of the option value would be 1-Lastname
And here's what I've tried.
<?php
if (isset($_POST['empSel'])){
$userid = $_POST['empSel'];
$userid = intval($userid);
echo '<script type="text/javascript"> alert('.$userid.')</script>';
}
?>
Now the javascript alert shows, but it echo 0. I think I am still not getting the value of my selected option
<option value="<?php echo $row2['id'] ?>">
This fixed it. In my previous code the option value was the surname...

Dynamic php rows gives values of 1st row only to javascript function when each row has its own dynamic values

I have been toying with this for a while now and i can not get each row to send its specific values that are displayed to a javascript function only the 1st rows values are sent no matter which row is clicked?
I need to send the values for each specific row dependng on the results of the mysql result.
Below is the code that i have which only sends the values of the 1st row.
<?php
require 'core/init.php';
$records = array();
$result = ("(SELECT * FROM message ORDER BY id DESC LIMIT 25)ORDER BY id ASC");
$results = ($db->query($result));
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
if(!count($records)){
echo 'no records';
}else{
?>
<table>
<?php
foreach ($records as $r){
?>
<tr>
<td><div id="modOptions" onclick="modOptions()"><?php echo escape($r->sender); ?></div></td>
<td><?php echo escape($r->message); ?></td>
<input type="hidden" id="modOptionsIp" value="<?php echo escape($r->ip); ?>"/>
<input type="hidden" id="modOptionsSender" value="<?php echo escape($r->sender); ?>"/>
<input type="hidden" id="modOptionsMessage" value="<?php echo escape($r->message); ?>"/>
</tr>
<?php
}
?>
</table>
<?php
}
?>
It displays everything ok just doesnt give each row its specific values
Any pointers are much appreciated.
Change the js modOptions function so it can take parameters
function modOptions(ip, sender, message) {
//ip sender and message are from the row you clicked on
}
and render the onclick like this:
onclick="modOptions('<?php echo escape($r->ip); ?>', '<?php echo escape($r->sender); ?>', '<?php echo escape($r->message); ?>' );"
those hidden fields you have now are useless

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