i want to insert both value and content of dropdown select into a database table. i can insert the value with no problem but i have no idea how to insert the content. i've been searching similar questions and probably it can be done by adding javascript. but i haven't learned about that yet so i have no clue how to use it.
<form action="hitung.php" method="POST" id="formid">
<?php
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {
?>
<tr>
<th><?php echo $row['nama'] ?></th>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
?>
<td>
<select class="btn-secondary" name="subkrt[<?php echo $i ?>][<?php echo $j ?>]" required>
<option value="" style="display:none;" required>-Pilih-</option>
<?php
$query = mysqli_query($conn, "SELECT pv_alternatif.pv_subkriteria, subkriteria.nama FROM pv_alternatif INNER JOIN subkriteria ON pv_alternatif.id_alternatif = subkriteria.id WHERE id_kriteria=$j+1");
while ($a = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $a['pv_subkriteria']; ?>"><?php echo $a['nama']; ?></option>
<?php
}
?>
</select>
</td>
<?php
}
}
?>
</tr>
</form>
so both value and content are fetched from two different tables of my database. and hitung.php is code to insert into database.
include 'koneksi.php';
include 'fungsi.php';
$jmlsub = array();
$qwery = mysqli_query($conn, "SELECT nilai FROM pv_kriteria");
while ($row = mysqli_fetch_array($qwery)){
$rows[] = $row['nilai'];
$jmlsub[] = 0;
}
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
$a = mysqli_query($conn, "SELECT * FROM nilai_alt");
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {?>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
if(isset($_POST['subkrt'][$i][$j])){
$matriks[$i][$j] = $_POST['subkrt'][$i][$j] * $rows[$j];
$value = $matriks[$i][$j];
$jmlsub[$i] += $value;
$id_alternatif = getIDAlternatif($i);
$id_kriteria = getKriteriaID($j);
if (mysqli_num_rows($a)==0) {
$b = "INSERT INTO nilai_alt VALUES('',$id_alternatif,$id_kriteria,$value)";
} else {
$b = "UPDATE nilai_alt SET nilai_alternatif=$value WHERE id_alternatif = $id_alternatif AND id_kriteria = $id_kriteria";
}
$rsult = mysqli_query($conn,$b);
if (!$rsult) {
echo "Gagal memasukkan / mengupdate nilai alternatif";
exit();
}
}
}
}
$jmlAlternatif = getJumlahSubKriteria();
for ($i=0; $i < ($jmlAlternatif); $i++) {
$id_alternatif = getIDAlternatif($i);
$query = "INSERT INTO ranking VALUES ($id_alternatif,$jmlsub[$i]) ON DUPLICATE KEY UPDATE nilai=$jmlsub[$i]";
$result = mysqli_query($conn,$query);
if (!$result) {
echo "Gagal mengupdate ranking";
exit();
}
}
header('Location: hasil_subkrt.php');
?>
tables:
Any help will be greatly appreciated. Thanks.
As you said you "can insert the value with no problem", so it is simple to pass all the value and content to the selected option value as a string
using json_encode(...), then in hitung.php you just convert it back to array or object using json_decode(...)
If you have a array, example:
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
Then just
<option value='<?php echo htmlentities(json_encode($a)); ?>'><?php echo $a['nama']; ?></option>
Then in your case in hitung.php,
...
$a = json_decode(html_entity_decode($_POST['subkrt'][$i][$j]), true);
...
More info, generally your code has nested loop and query database in loop, you need to think more about better query way to reduce number of loops to increase performance.
Edited and added an example using some php functions that might help you:
<?php
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
$str = htmlentities(json_encode($a));
$a2 = json_decode(html_entity_decode($str), true);
print_r($a2);
?>
Related
<link type="text/css" rel="stylesheet" href="style_downloads.css" />
<script>
function theFunction(e){
var x = e.target.innerHTML;
document.write(x);
}
</script>
<a onclick="theFunction(event)" href="">Electromagnetic Theory</a>
<a onclick="theFunction(event)" href="">Manufacturing Technology-I</a>
<?php
$con = mysqli_connect('localhost', 'root');
if (!$con) echo "Connection Failed";
mysqli_select_db($con, 'test') or die(mysqli_error($con));
$q = "SELECT * FROM tb1";
mysqli_query($con, $q) or die(mysqli_error($con));
$result = mysqli_query($con, $q);
$num = mysqli_num_rows($result);
for ($i = 1; $i <= $num; $i++) {
$row = mysqli_fetch_array($result);
if(?>
<script>x</script>
<?php==$row['coursename'])
{ ?>
<div id="downloads"> <span id="pdfname"><?php echo $row['pdfname'] ?></span> <img src="download.png" id="downloadbtn"> </div>
<?php
}
}
mysqli_close($con);
?>
Here I want to compare var x of js to $row['coursename'] ie mysql db table entry.
Basically this code is targetting to display db table entry according to onclick event.
Example:
When I click on Electromagnetic Theory, File displayed on page should be correspending to this course name only.
<link type="text/css" rel="stylesheet" href="style_downloads.css" />
<script>
function theFunction(e)
{
var itemName = e.target.innerHTML;
$.ajax({
url : "/ajaxAction.php",
type : "POST",
data : {'itemName':itemName},
dataType: 'json',
success: function (response) {
console.log("response",response)
if(response.type == "success") {
$("#downloads").html('');
$("#downloads").html(response.result);
return false;
}
}
});
}
</script>
<a onclick="theFunction(event)" href="">Electromagnetic Theory</a>
<a onclick="theFunction(event)" href="">Manufacturing Technology-I</a>
<div id="downloads">
<span id="pdfname"><?php echo $row['pdfname'] ?></span>
<img src="download.png" id="downloadbtn">
</div>
<?php
create file ajaxAction.php
incluede connection.php
$itemName = $_POST['itemName'];
$con = mysqli_connect('localhost', 'root');
if (!$con)
echo "Connection Failed";
mysqli_select_db($con, 'test') or die(mysqli_error($con));
$q = "SELECT * FROM tb1";
mysqli_query($con, $q) or die(mysqli_error($con));
$result = mysqli_query($con, $q);
$num = mysqli_num_rows($result);
for ($i = 1; $i <= $num; $i++) {
$row = mysqli_fetch_array($result);
if($itemName == $row['coursename'])
{
$res = ' <span id="pdfname"><?php echo $row['pdfname'] ?></span>
<img src="download.png" id="downloadbtn">';
}
}
echo json_encode("type":"success","result":$res);
mysqli_close($con);
?>
I have a code format for every category selected from the drop down menu.
Say for Category A, the code to be retrieved in the textbox is "A - 1001" and for Category B, "B - 2003". My problem is that I can't increment the code into "A - 1002" for category A, for example because it's already read as string.
How can I retrieve a formatted code from the database which will increment its value?
Here's my code for the selection of category and for the retrieval of the code:
Category:
<script type="text/javascript">
function GetSelected (selectTag) {
var selIndexes = "";
for (var i = 0; i < selectTag.options.length; i++) {
var optionTag = selectTag.options[i];
if (optionTag.selected) {
if (selIndexes.length > 0)
selIndexes += ", ";
selIndexes = optionTag.value;
}
}
var info = document.getElementById ("viocode");
if (selIndexes.length > 0) {
viocode.innerHTML = selIndexes;
}
else {
info.innerHTML = "There is no selected option";
}
}
</script>
<select option="single" name= "viocat" id="viocat" onchange="GetSelected (this);" class = "form-control">
<option>Choose category ...</option>
<option value="
<?php
$con = ...
$sql = "SELECTcategory, MAX(code) AS highest_id FROM tbl_name where category = 1";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "A - " .$i;
$cat = 1;
}
?>">DlR</option>
<option value="
<?php
$con = ...
$sql = "SELECT category, MAX(code) AS highest_id FROM tbl_name where category = 2";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "B - " .$i;
$cat = 2;
}
?>">B</option>
<option value="
<?php
$con = ...
$sql = "SELECT category, MAX(code) AS highest_id FROM tbl_name where category = 3";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['highest_id'];
$i++;
echo "C - " .$i;
$cat = 3;
}
?>">C</option>
</select>
And here's the codes for the textbox where the formatted code is to be displayed:
Violation Code:
<strong><text type= "text" id="viocode" name="viocode" />
If I understand it correctly, you need to increment a number ($i), from $row['highest_id'].
The extra line will try to parse the $row['highest_id'] as an int, then your code uses it, and the last line of the while loop increments $i with 1.
while($row = mysql_fetch_array($result))
{
$i = intval($row['highest_id']);
//$i = $row['highest_id'];
echo "A - " .$i;
$cat = 1;
$i++;
}
Try parsing your variable to integer.
Instead of using $row['highest_id']
use: $i = intval($row['highest_id'];
I have this jQuery form being outputted in a PHP while loop if the button has not previously been clicked and just an image with the value if it has, the function is like facebooks like button where when the user clicks the button the icon changes so its not clickable any longer and the value increments by 1. The form submission works but I cannot seem to update the icon image and value count in the feed without effecting all the other buttons and values in the feed… I tried jQuery replaceWith() but it replaces all the #bumpCont divs in the feed…
index.php
<div class="images">
<?php
while($row = $result2->fetch_assoc()){
$path = $row['path'];
$user = $row['user'];
$id = $row['id'];
$desc = $row['desc'];
$update = $row['update_date'];
$bump = $row['bump'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
?>
<?php if(empty($desc)){}else{?><div id="desc"><?php echo $desc;?></div><?php }?>
<img id="pic" src="uploads/<?php echo $path;?>"/>
<div id="userCont">
<div id="user"><a rel="external" href="user_profile.php?user='.$user.'"><?php echo $user;?></a></div>
<div id="timer"><?php echo $timer;?></div>
<?php
if(in_array($path, $mypath)) {
echo '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">'.$bump.'</span></div>';
}else{
echo '<form method="post" id="bumpF" data-ajax="false">';
echo '<input name="id" data-ajax="false" id="field_'.$id.'" type="hidden" value="'.$id.'" />';
echo '<div id="bumpCont"><input type="image" style="height:55px;right:8px;top: 2px;position: relative; " id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm('.$id.');" value="Send" /><span id="bumpCount">'.$bump.'</span></div>';
echo ' </form>';
}
?>
</div>
<?php
}
?>
//Submit Form
function SubmitForm(id) {
event.preventDefault();
var name = $('#field_'+id).val();
console.log(name);
$.post("bump.php", {name: name},
function(data) {
$( "#bumpCont" ).replaceWith( '<div id="bumpCont"><img id="bump" style="height:55px;right:8px;top: 2px;position: relative;" src="../img/bumpg.png"/><span id="bumpCount">' + data + '</span></div>' );
}
Bump.php -
$id = $_POST['name'];
$sessionUser = $_SESSION['userSession'];
// GET USERNAME
$sql = "SELECT * FROM userbase WHERE user_id='$sessionUser'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myname = $row['username'];
}
}
$bump = 1;
$sql = "SELECT * FROM images WHERE id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bump = $row['bump'];
$path = $row['path'];
$desc = $row['desc'];
$post_user = $row['user'];
$bump++;
}
}
$bumpC = 0;
$sql = "SELECT * FROM bumped WHERE path='$path' AND myname ='$myname'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$bumpC++;
}
}
echo $bump;
if($bumpC >= 1){
}else{
$sql = "INSERT INTO `bumped` ( `myname`,`path`, `description`, `post_user`) VALUES ( '$myname','$path', '$desc', '$post_user')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "UPDATE images SET bump=$bump WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
}
First look shows me a problem of Elements with same ID in loop.
You could have same class to multiple elements.
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
Use $(this)
Based on the click on particular element, you can change contents.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html) + 1);
});
Hope this helps you.
$('.bumpCount').click(function(){
$(this).html(parseInt($(this).html()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bumpCont"><span class="bumpCount">1</span></div>
<div class="bumpCont"><span class="bumpCount">2</span></div>
i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";
i would like to seek some help with my code because my current code wont work...i found this plugin code from this site click here...as of now all are not working even the first combobox filtration...can anyone help me get this code work please.
index.php:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.js"></script>
</head>
<body>
<form>
<select name="position" id="position"></select>
<select name="salary_grade" id="salary_grade"></select>
<select name="salary" id="salary"></select>
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#position").jCombo({ url: "getPosition.php", selected_value : '150' } );
$("#salary_grade").jCombo({ url: "getSalary_Grade.php?sgid=",
parent: "#position",
selected_value: '178'
});
$("#salary").jCombo({ url: "getSalary.php?salaryid=",
parent: "#salary_grade",
selected_value: '630'
});
});
</script>
</body>
</html>
getPosition.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Execute Query in the right order
//(value,text)
$query = "SELECT tcode, position FROM positions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getSalary_Grade.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$sgid = !empty($_GET['tcode'])
?intval($_GET['tcode']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salary_grades WHERE salary_grades.id = '$sgid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>
getSalary.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$salaryid = !empty($_GET['id'])
?intval($_GET['id']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE salarys.id = '$salaryid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>
This should work:
getSalary.php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$salaryid = !empty($_GET['salaryid'])
?intval($_GET['salaryid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE id = $salaryid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}
getSalary_Grades.php
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$sgid = !empty($_GET['sgid'])
?intval($_GET['sgid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id, salary FROM salary_grades WHERE id = $sgid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}