1 out of 3 dropdown list creating conflict using mysql - javascript

Ok so here are the tables I have:
departments associates
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| dep_id | dep_name | date_added | | asso_id | asso_name | dep_id | date_added |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| 1 | Pick a Department| Date | | 1 | A Associate | 2 | Date |
| 2 | Department A | Date | | 2 | B Associate | 3 | Date |
| 3 | Department B | Date | | 3 | C Associate | 4 | Date |
| 4 | Department C | Date | | 4 | D Associate | 5 | Date |
| 5 | Department D | Date | | 5 | A Associate 2 | 2 | Date |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
key_list key_log
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| key_id | key_name | date_added | | id | key_assigned | key_status | assigned_to | assigned_by |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| 1 | Key 1 | Date | | 1 | Key 1 | 0 | A Associate | logged in name |
| 2 | Key 2 | Date | | 2 | Key 4 | 0 | B Associate | logged in name |
| 3 | Key 3 | Date | | | | | | |
| 4 | Key 4 | Date | | | | | | |
| 5 | Key 5 | Date | | | | | | |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
So I'm trying to create a key log where I can store key names and associate names, and if the key was logged out or in. My first issue came when trying to link dropdown menus for departments and associates. I learned that you don't put comas for joins and someone suggested to just go ahead and use multiple querys.
So after some research I went about it this way:
<?php
$dbhost_name = "localhost";
$database = "db_name";
$username = "user_name";
$password = "password";
try {
$dbo = new PDO('mysql:host='.$dbhost_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
</head>
<body>
<?Php
#$cat=$_GET['cat']; // Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
}
$quer3="SELECT DISTINCT key_name, key_id FROM key_iv order by key_name";
$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }
echo "<form method=post name=f1 action='dd-check.php'>";
// Starting of first drop down
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
// This will end the first drop down list
// Starting of second drop downlist
echo "<select name='subcat'><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
// This will end the second drop down list
echo "<input type=submit value=Submit>";
echo "</form>";
?>
</body>
</html>
My problem with this is that when you select a key, and after select a department, the key originally selected gets reset and you have to go back and select the key again. You might say o well just place the keys drop down at the end. Well my intention is later to be able to select a key and with ajax or php check if the key status of that key is 0 (logged out) or 1 (logged back in), if it's on status 0, automatically select the radio button for status 1, and vise versa.
After this I did more research and found this Populate another select dropdown from database based on dropdown selection and so decided to go with this approach:
<?php
$db = new mysqli('localhost', 'carlos', 'Security5', 'testing');
$query = "SELECT dep_id, dep_name FROM department";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['dep_id'], "val" => $row['dep_name']);
}
$query = "SELECT ass_id, dep_id, ass_name FROM associates";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['dep_id']][] = array("id" => $row['ass_id'], "val" => $row['ass_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
The problem with this is again when I place the first drop down before the other two, the other two don't work, and in this case completely disappear. When I place it after the two drop downs, everything works. I know, why am I not placing it after to fix it. Well like I said before, I need this to work for specifically adding other functionality later. Than and I refuse to accept that this can't be done. Can anyone tell me why this is not working for either method, and for that matter which is the better method.

I think the problem with your second attempt is you get key_name and key_id from your query, but where you write out the values in the options you refer to key_name and id (not key_id):
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
So, fixing that up (and the lack of quotes around names, and lack of escaping of data onto HTML):
<?php
$querykeys = "SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
printf("<select name='key_names'>\n");
printf("<option value=''>Select Key</option>\n");
foreach ($dbo->query($querykeys) as $row) {
printf("<option value='%s'>%s</option>",
htmlentities($row['key_id'], ENT_QUOTES),
htmlentities($row['key_name'], ENT_QUOTES)
);
}
echo "</select>\n";
?>

Related

Dynamic dependent dropdown php how to compare two strings?

I am trying to compare two strings using ajax and php. I am based on this code https://github.com/webhostguru/dynamic-drop-down. I change the code on the ajaxdata.php file and it looks like this
<?php
include_once 'config.php';
if (isset($_POST['country_id'])) {
$query = "SELECT * FROM state where state_name=".$_POST['country_name'];
$result = $db->query($query);
if ($result->num_rows > 0 ) {
echo '<option value="">Select State</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value='.$row['id'].'>'.$row['state_name'].'</option>';
}
}else{
echo '<option>No State Found!</option>';
}
The rest of the code is the same. I change also some of sql tables and i have a state named India to compare the strings with country (India also) but it doesn't work. Any ideas?
Thank you in advance!!!
To use a prepared statement you can try like this:
<?php
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
require 'config.php';
$query = 'select `id`, `state_name` from `state` where `state_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( $output );
}
?>
Based upon the database cited but modified slightly for table names:
mysql> select * from tbl_country;
+----+--------------+---------------------+
| id | country_name | time_stamp |
+----+--------------+---------------------+
| 1 | India | 2019-12-05 16:29:16 |
| 2 | USA | 2019-12-05 16:29:16 |
| 3 | Australia | 2019-12-05 16:29:44 |
| 4 | England | 2019-12-05 16:29:44 |
+----+--------------+---------------------+
mysql> select * from tbl_state;
+----+-----------------+------+---------------------+
| id | state_name | c_id | time_stamp |
+----+-----------------+------+---------------------+
| 1 | Delhi | 1 | 2019-12-05 16:30:15 |
| 2 | Maharashtra | 1 | 2019-12-05 16:30:15 |
| 5 | South Australia | 3 | 2019-12-05 17:02:22 |
| 6 | West Australia | 3 | 2019-12-05 17:02:22 |
+----+-----------------+------+---------------------+
mysql> select * from tbl_city;
+----+------------+------+---------------------+
| id | city_name | s_id | time_stamp |
+----+------------+------+---------------------+
| 1 | East Delhi | 1 | 2019-12-05 16:31:42 |
| 2 | West Delhi | 1 | 2019-12-05 16:31:42 |
| 3 | Mumbai | 2 | 2019-12-05 16:32:49 |
| 4 | Pune | 2 | 2019-12-05 16:32:49 |
| 5 | Adelaide | 5 | 2019-12-05 17:03:01 |
+----+------------+------+---------------------+
And a marginally different piece of PHP
<?php
#hardcode POST values for testing...
$_POST['country_id']=1;
$_POST['country_name']='India';
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
#require 'config.php';
# pertinent to my system
require '../../dbo/db-conn-details.php';
require '../../dbo/mysqli-conn.php';
# joining all tables
$query='select distinct ct.`id`,s.`state_name` from `tbl_country` ct
join `tbl_state` s on s.`c_id`=ct.`id`
join `tbl_city` c on c.`s_id`=s.`id`
where ct.`country_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( sprintf('<select>%s</select>',$output ) );
}
?>
Results in generated HTML like this:
<select>
<option selected="" hidden="" disabled="">Please Select State</option>
<option value="1">Delhi</option>
<option value="1">Maharashtra</option>
</select>

How can I read the checked state of a checkbox within the cell of a dynamically created HTML table

I am using JS to determine the checked state of checkboxes which are contained within cells of a table which has been loaded dynamically into a web page.
The page comprises 2 fieldsets:-
+-SelectFieldset-----------------------------+
| <param1> <param2> { Load button } |
| {Update button} |
+--------------------------------------------+
+-ResultFieldset id=resultFS-----------------+
| Ref_ID Description Ready |
| +-resultTable id=outTable----------------+ |
| | 123 chair [ ] | |
| | 167 dresser [ ] | |
| | 231 sofa [ ] | |
| | ... etc... | |
| +----------------------------------------+ |
+--------------------------------------------+
Notes "[ ]" above depicts a table cell containing an input with type = checkbox;
param1, param2 are dropdown selectors
Initially the ResultFieldset is empty; and is loaded when the "Load" button is clicked (using a JQuery post statement) after the select parameters have been specified.
$.post("../listProducts.php", {
AccName: account,
From: startDate}, function(data){
$("#resultFS").after(data);
});
Once the resultTable is displayed, the user checks the checkboxes as relevant in the table rows.
Subsequently, when the "Update" button is clicked I need to loop through each table row, read that row's Ref_ID value and then, depending on the checked status of the associated checkbox, post an Update to the specified row of a MySQL table.
The code to loop through the table is:-
$("#btnUpdate").on('click', function() {
for (var i=0, row; row = outTable.rows[i]; i++) {
var rowRef = row.cells[1].textContent;
console.log( "Ref_ID = " + rowRef);
var isChecked = 0;
if (row.cells[2].firstChild.checked = true){
isChecked = 1;
// update MySQL table using rowRef;
};
console.log( "Ref_ID = " + rowRef + " Ready = " + isChecked);
};
};
This code logs the Ref_ID values as expected but I'm unable to determine the checkbox state in any row. (The checkboxes are behaving as expected on the webpage - clicking sets & unsets them.)
Please advise on how I should code for this (using either JS or JQuery). Thanks..

Display option selected with codeigniter

I want to ask for my code option selected with 2 tabel in page register
table prodi
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id_prodi | varchar(3) | NO | PRI | NULL | |
| nama_prodi | varchar(30) | NO | | NULL | |
| id_fakultas | varchar(3) | NO | MUL | NULL | |
| id | int(2) | NO | MUL | NULL | |
+-------------+-------------+------+-----+---------+-------+
and
table jurusan
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| id_fakultas | varchar(3) | NO | PRI | NULL | |
| nama_fakultas | varchar(40) | NO | | NULL | |
+---------------+-------------+------+-----+---------+-------+
here's view :
<label for="fakultas">Fakultas : </label>
<select id="fakultas" name="fakultas_user" onChange="fakultas">
<?php
foreach ($qfakultas as $fakultas) {
echo "<option value=".$fakultas->kd_fakultas.">".$fakultas->nama_fakultas."</option>";
}
?>
</select>
<hr>
<label for="jurusan">Jurusan : </label>
<select id="jurusan" name="jurusan_user" onChange="jurusan">
<?php
foreach ($qprodi as $prodi) {
echo "<option value=".$prodi->kd_prodi.">".$prodi->nama_prodi."</option>";
}
?>
</select>
but I will display 'nama_prodi' based on 'id_fakultas"
register with option value
How to display when I click 'nama_fakultas' then display 'nama_prodi' based on 'id_fakultas' ?
Thanks
Here is the Ajax code that I can help, only to get nama_prodi based on id_falkutas.
You can use this code for your project, there is something you need to do. Not just copy the code. Just a few step (ID Lang : Jangan dicopy mentah2, hanya beberapa langkah saja untuk edit).
Change YOUR_URL_HERE into your base_url() or create var for it.
Change nama_controller into your controller name in CI_Controller
Change nama_fungsi into your function to get the data from your model (database). Example : ambil_data_jurusan.
Remove your foreach - echo <option> and onchange from your view.
Add the script into your view files or create a new .js file.
Please help me to mark as correct answer if this code helped you. ( tolong dibantu gan )
See Code Example :
<script>
$("#falkutas").on('change', function() {
$.ajax({
type:"POST",
url:'YOUR_URL_HERE/nama_controller/nama_fungsi',
data:{"falkutas_user":falkutas_user,"csrf_token":$("input[name=csrf_token]").val()},
dataType:'json',
success: function(result) {
for(var i=0; i<result.length; i++) {
res += '<option value="'+result[i]['id_prodi']+'">'+result[i]['nama_prodi']+'</option>';
}
$(document).ready(function() {
$("#prodi").html(res);
});
},
error: function(result) {
$(document).ready(function() {
$("#prodi").html(''); //empty select value
});
}
});
}
</script>
Then, in your function code :
// Inside function ambil_data_jurusan(), harusnya sudah jalan kalau gini
$return = $this->model->get_jurusan($this->input->post('falkutas',TRUE));
if(count($return)>0) {
echo json_encode($return);
}
In your view, just let select empty like this.
<select id="jurusan" name="jurusan_user">
</select>

Select the opposite of the union data

I had product, vendor, vendor's available day and booking tables. Currently, my search function only can search through vendor available day, but not search through booking table. I used left joins between vendor and vendor available day and compare with the selected day, time and hour. The search result works. How do I search through booking table?
Product Table
id | vendor_id | title | description
Vendor Table
id | name
Vendor Available Table
id | vendor_id | d_day | d_start_hour | d_start_minute | d_end_hour | d_end_minute
Booking Table
id | vendor_id | d_date | d_day | d_start_hour | _start_minute
Below is how I select product based on the selected day, start_hour and start_minute:
SELECT * FROM product
LEFT JOIN ( SELECT * FROM vendor GROUP BY id ) vendor
ON vendor.id = product.vendor_id
LEFT JOIN ( SELECT * FROM vendor_available GROUP BY id) vendor_available
ON vendor_available.vendor_id = product.vendor_id
WHERE ( d_day = '4'
AND (CONCAT(d_start_hour, '.' , d_start_minute) + 0.0) <= '12.15'
AND (CONCAT(d_end_hour, '.', d_end_minute) + 0.0) >= '12.15')
4 is the selected day and 12.15 is the selected hour and selected minute on the client side.
When the user selects 12.15 which is 12.15pm, the query will check which product is available between the vendor available time.
How do I use opposite union with booking table, so that the product which already booked doesn't display to users?
When using LEFT JOIN tbl, it is normal to add this to the WHERE clause (not the ON clause)
AND tbl.id IS NULL
This says that you want to return results only when the is no row in tbl.

Joining recent database rows in PHP loop

Let's assume I have a MySQL structure like this...
+--------------+--------------------+-------------------+
| tdate | tuser | tvalue |
+--------------+--------------------+-------------------+
| 11:16:48 | John | 10 |
+--------------+--------------------+-------------------+
| 11:16:38 | John | 40 |
+--------------+--------------------+-------------------+
| 11:16:28 | Lisa | 50 |
+--------------+--------------------+-------------------+
| 10:16:48 | Lisa | 20 |
+--------------+--------------------+-------------------+
and a php query like this:
<?php
$username = 'test';
$sql=mysqli_query($db,"SELECT * FROM t ORDER BY tid DESC LIMIT 20");
while($row=mysqli_fetch_array($sql))
{
$tuser= $row['tuser'];
$tvalue= $row['tvalue'];
$tdate= $row['tdate'];
?>
<div id="<?php echo $tvalue; ?>" class="message_box">
<?php echo $tdate; ?> -
<?php echo $tvalue; ?> -
<?php echo $tuser; ?>
</div>
<?php
}
?>
This currently lists the mysql table by each row like this:
2016-02-22 11:16:48 - 10 - John
2016-02-22 11:16:38 - 40 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
I would like to see it like this:
2016-02-22 11:16:48 - 50 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
Meaning that loop would have to sum up values in cases where the new row was created within 60 seconds (for the same user).. Lisa has two rows, but since there is one hour timestamp difference it would have to be listed as usual... It would need it to update automaticaly, meaning that it would show value of 40 for John initially, but after 10 seconds when the new row would be added it would have to update to 50 accordingly. There is also the issue of MYSQL QUERY LIMIT of 20 which could break up rows that were inserted within 60 seconds and give false total value calculation.. I know it's a hard one, but does anyone has a simple solution for this?
Thanks to Asur I currently have this:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY EXTRACT(DAY_HOUR FROM tdate),tuser
ORDER BY tid DESC
LIMIT 20;
but the problem is that if the last database row is JOHN, he will not be listed out last if there is already one John row above that in the same hour..
IF I HAVE:
JOHN 10
GEORGE 10
GEORGE 10
JOHN 10
It will list:
JOHN 20
GEORGE 20
And it should be the other way arround, where the last row counts:
GEORGE 20
JOHN 20
I would recommend you to do it directly in the sql query as follows:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY time,tuser
ORDER BY tid DESC
LIMIT 20;
This is long way better in terms of optimization and spent time.
replace this query:
SELECT * FROM t ORDER BY tid DESC LIMIT 20
with this:
SELECT tdate , sum(tvalue), tuser FROM t
group by tuser, DATE_FORMAT(tdate , '%Y-%m-%d %h:%i')
ORDER BY tid DESC LIMIT 20

Categories