Increment a Formatted Code in PHP - javascript

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'];

Related

how to insert both value and content of dropdown select into database?

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);
?>

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

How to change the name, but not the value of a dynamically filled select list?

I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.
This is how I'm filling the select list with the real column names at the moment:
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
And this is the code that get's the data outof my database:
<?PHP
require "opendb.php";
$query = "select table_name
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}
echo json_encode($table_names);
require "closedb.php";
?>
Update
This is what my database table looks like:
So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.
Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.
<?PHP
require "opendb.php";
$query = "select table_name,table_alias
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>
Then in your client side code simply output the table_alias as option name and table_name as option value.
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
html
<select id="xoxo_select">
<option value="foo_value">foo</option>
<option value="xoxo_value">xoxo</option>
</select>
js
$('#xoxo_select option[value="xoxo_value"]').text('bar'); // change name of option
$('#xoxo_select option[value="xoxo_value"]').attr('value', 'bar_value'); // change value of option
jsfiddle https://jsfiddle.net/tg126u7g/
Change in fetch data from DB:
<?PHP
require "opendb.php";
$query = "select table_name,table_alis
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
$i=0;
while ($row = pg_fetch_array($data))
{
array_push($table_names[$i], $row["table_name"]);
$i++;
}
echo json_encode($table_names);
require "closedb.php";
?>
Then Change in javascript code:
optionsTables += "<option value='" + data[i][0] + "'>" + data[i][1] + "</option>";

Grab two values in loop, check box and variable. Only grabbing checkbox? php w screenshot

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']})";

Ajax POST function returning the same result

I just encountered a problem trying to populate two dropdown selection menus using jQuery, Ajax and php. The code keeps loading the same value from database even if a different option is selected from the dropdown menu. Here is a snippet of the code
test.html
<html>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<body>
<form method="post" action="self.php">
<table>
<tr>
<td><div><label><strong>class:</strong></label></div></td>
<td><div><select name="class_id" id="class_id_0">
<option value="" selected>Select a Class</option>
<option value="1">Nursery</option>
<option value="2">Primary</option>
<option value="3">Secondary</option>
</select></div></td>
</tr>
<tr>
<td><div><label><strong>Sub-Class:</strong></label></div></td>
<td><div><select name="sub_class_id" id="sub_class_id_0">
<option value="">Select a Sub - Class</option>
</select></div></td>
</tr>
<tr>
<td><div><label><strong>Subject:</strong></label></div></td>
<td><div><select name="subject_id" id="subject_id_0">
<option value="">Select a Subject</option>
</select></div></td>
</tr>
</table>
</form>
</body>
</html>
JQuery
<script>
(function($){
$("#class_id_0").change(function(){
var str = "";
var type = "sub_class";
$( "#class_id_0 option:selected" ).each(function() {
str += $( this ).val() + " ";
});
$.post( "data.php",{class_id:parseInt(str),type:""+type}).done(function(data){
alert(str);
alert( "Data Loaded:" + data );
$("#sub_class_id_0").html(data);
});
});
$("#sub_class_id_0").change(function(){
var str = "";
var type = "subject";
$( "#sub_class_id_0 option:selected" ).each(function() {
str += $( this ).val() + " ";
});
$.post( "data.php",{sub_class_id:parseInt(str),type:""+type}).done(function(data){
alert(str);
alert( "Data Loaded:" + data );
$("#subject_id_0").html(data);
});
});
})(jQuery);
</script>
data.php
<?php
$options = "";
$query = "";
$type = isset($_REQUEST["type"]);
switch($type){
case "sub_class":
$sub_class_id = intval($_REQUEST["sub_class_id"]);
$default_value = "";
$default_text = "Select a Sub - Class";
$options = "<option value='".$default_value."'>".$default_text."</option>";
if($class_id == "" || $class_id == 0)
{
$options = "<option value = >Select a Class First</option>";
}
$con = mysql_connect('localhost', 'root', '');
$database = mysql_select_db('admin_glisten');
$sql="SELECT sub_class_id,sub_class FROM sub_class WHERE class_id = '".$class_id."'";
$result = mysql_query($sql);
if (!$result) {
die("Query failed: " . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
$options .= "<option value='".$row['sub_class_id']."'>".$row['sub_class']."</option>";
}
echo $options;
mysql_close($con);
break;
case "subject":
$sub_class_id = intval($_REQUEST["sub_class_id"]);
$default_value = "";
$default_text = "Select a Subject";
$options = "<option value='".$default_value."'>".$default_text."</option>";
if($sub_class_id == "" || $sub_class_id == 0)
{
$options = "<option value = >Select a Sub - Class First</option>";
}
$con = mysql_connect('localhost', 'root', '');
$database = mysql_select_db('admin_glisten');
$sql="SELECT subject_scheduler.subject_id,subject.subject_id,subject.name FROM subject_scheduler INNER JOIN subject ON subject_scheduler.subject_id=subject.subject_id WHERE sub_class_id = '".$sub_class_id."'";
$result = mysql_query($sql);
if (!$result) {
die("Query failed: " . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
$options .= "<option value='".$row['subject_id']."'>".$row['name']."</option>";
}
echo $options;
mysql_close($con);
break;
default:
}
?>
PS
Never mind my insecure code am just trying to get it to work. Any help will be gratefully appreciated, as i have been on this for the past couple of hours now.
You are using $class_id variable to query the database, but $class_id is always going to be the same. Here is why:
On line 4 of PHP code
$class_id = intval(isset($_REQUEST["class_id"]));
Intval returns an integer, which is fine, however, you are also calling isset, which returns a boolean. In most cases isset results in true and then intval results in 1.
So in fact your query is always:
SELECT sub_class_id,sub_class FROM sub_class WHERE class_id = '1';

Categories

Resources