Tips for resolving an error in PHP and MYSQL code where data is being selected from the incorrect table in the database

I am working on a PHP code with MYSQL. It involves selecting data from the database using a dropdown list with AJAX and displaying the results on the screen. I have three dropdown lists that are dependent on each other and each dropdown has its own table to select from:

  • site_info
  • owner_info
  • company_info

Note: The third table only has 6 values.

The issue arises when the user selects an option from the first dropdown, causing the third dropdown to display results from the second table.

If anyone could assist me in resolving this problem, it would be greatly appreciated.

search_info_location.php

 <td><select id="site_name"  name = "site_name">
                      <option value="">Select Site</option>
                 <?php


                     $query_site_name =$wpdb->get_results("select DISTINCT 
                        i.siteNAME, 
                        i.ownerID, 
                        i.companyID,
                        o.ownerNAME,
                        x.companyNAME
                       from site_info i
                       LEFT  
                       JOIN owner_info o
                       on i.ownerID = o.ownerID
                       LEFT  
                       JOIN company_info x
                       on i.companyID = x.companyID
                       ");
                      foreach($query_site_name as $row)
                      {

                          echo "<option value = '".$row ->companyID.",".$row ->ownerID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";


                      } 


                 ?>

                </select></td>

<!--create  dropdown list owner names-->
                <td><select id="owner_name"  name ="owner_name">
                <option value="">Select Owner</option>
                </select></td>

<!--create  dropdown list Company names-->
                <td><select id="Company_name"  name ="Company_name">
                <option value="">Select Company</option>
                </select></td>



$sql = $wpdb->prepare("select i.siteID
     , i.siteNAME
     , i.equipmentTYPE
     , c.latitude
     , c.longitude
     , c.height 
     , o.ownerNAME
     , o.ownerCONTACT
     , x.companyNAME
     , y.subcontractorCOMPANY
     , y.subcontractorNAME
     , y.subcontractorCONTACT
  from site_info i
  LEFT  
  JOIN owner_info o
    on i.ownerID = o.ownerID
  LEFT  
  JOIN company_info x
    on i.companyID = x.companyID
  LEFT 
  JOIN subcontractor_info y
    on i.subcontractorID = y.subcontractorID
    LEFT JOIN site_coordinates2 c
    on i.siteID=c.siteID 
    where 
    i.siteNAME = %s
    AND 
    o.ownerNAME = %s
    AND 
    x.companyNAME = %s
   ",$site_name,$owner_name,$company_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);

<script type="text/javascript">

// make Dropdownlist depend on each other
$(document).ready(function(){


 // depend owner name on site name  
   $('#site_name').change(function(){
     var arrayId = $(this).val().split(",");
     if(arrayId != ""){
       var ownerID = arrayId[0];    
       var companyID = arrayId[1];  

     $.ajax({
      url:"<?php echo get_stylesheet_directory_uri(); ?>/dropdown_fetch_owner.php",
       method:"POST",
       data:{ownerID:ownerID,companyID:companyID},
       dataType:"text",
       success:function(data){
                 var Response = data.split("--");
                 $('#owner_name').html(Response[2]);
                 $('#Company_name').html(Response[4]);
        }
     });


   }


  });

});

</script>

dropdown_fetch.php

<?php
 include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-load.php');
 global $wpdb,$Owner_name,$Company_name;

   $sql =$wpdb->get_results("select ownerID, ownerNAME from owner_info where ownerID = '".$_POST['ownerID']."' ORDER BY ownerNAME");
   $Owner_name = '--Owner--';

  foreach($sql as $row){


      $Owner_name.= "<option value ='".$row ->ownerID."'>".$row->ownerNAME."</option>";
  }
  echo $Owner_name;


   $sql =$wpdb->get_results("select companyID, companyNAME from company_info where companyID = '".$_POST['companyID']."' ORDER BY companyNAME");
   $Company_name = '--Company--';
   var_dump($sql);


   foreach($sql as $row){

     $Company_name.= "<option value ='".$row ->companyID."'>".$row->companyNAME."</option>";
   }
   echo $Company_name;
   exit();

?>

https://i.stack.imgur.com/pcG37.png

The maximum number of the companyID must be 6, however, it displays 166, which exists in the owner_info table.

Answer №1

Could these values be mistakenly reversed?

   var idOwner = arrayId[0];    //0
   var idCompany = arrayId[1];  //1

Are they being assigned in the wrong order...

echo "<option value = '".$row ->companyID.",".$row ->ownerID.",".$row ->siteNAME."'>".$row->siteNAME."</option>";

It seems like it should actually be

   var idCompany = arrayId[0];
   var idOwner = arrayId[1];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

Split the text using the newline character (' ') and not the double newline character (' ')

Looking to create a filter that separates all \n and combines them back as \n\n. Is it possible to only target the single \n without affecting the double \n\n? Currently, the issue arises when the input field loses focus, caus ...

Extract a value from a json document

Hey there! I'm looking to create an unwhitelist command. When a user is mentioned or their ID is provided, I want it to be removed from the JSON file without checking if the ID exists. Do you have any suggestions on how to accomplish this? Here is my ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

The error message displayed in Andriod Studio states that there is an issue converting the value "<br" of type java.lang.String to a JSONObject,

I am currently in the process of developing an android app using Android Studio that involves sending data from a User Registration activity to a database. The goal is for the user to input all the required information, click the register button, and have ...

Utilizing the Power of GrapesJs in Vue3

Recently, I attempted to integrate the GrapesJS editor into my Vue.js project, but encountered some difficulties. The editor was not visible in the browser, and the designated tag for the editor appeared empty. Here is my editor configuration: <template ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...

An issue arises when attempting to integrate ajax with colorbox

I am currently facing an issue with a WordPress plugin designed for playing videos. It seems that the developer who created it is no longer available, and now the play video button has stopped working. Upon further investigation using Firebug, I noticed ...

Avoid refreshing the page when clicking on an anchor tag in Vue.js

I have the code below in my Vue file. The problem I am encountering is that the page reloads whenever I click on the link. I have tried using event.preventDefault() but it did not solve the issue. Can someone please help me identify what I am doing wrong ...

utilize ajax to upload documents in codeigniter

I am facing an issue with uploading files using ajax in Codeigniter. The problem arises when I try to upload videos, sometimes it works and sometimes it doesn't. Despite configuring the max_size to 1000000 and even setting it to 0 for no limit, I stil ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

Creating a zip file from database or binary file content using PHP

I'm looking to create a zip file using PHP, however my source files are all stored in databases rather than on disk. The content of the files I need to pack is saved as binary data in one database, while the metadata is stored in another. I've ...

Receiving and transmitting messages repeatedly in Discord.JS

Currently, I am developing a simple bot. Interestingly, the bot seems to be responding multiple times to a single command. Here is the code snippet: const Discord = require('discord.js'); var bot = new Discord.Client(); const PREFIX = "+"; var ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...