0

This is my code:

//Logic....
$companyId = $_POST['var1'];
global $db;
$query = "SELECT firstname, surname FROM contact WHERE directorycompany_id = " . $companyId;
$result = $db->query($query);
$total = $result->num_rows;
?>

<!-- HTML -->
<option value=""><?= $total; ?></option>

I am trying to make an ajax request when a user selects an option from a dropdown menu. The idea is that the company id is passed as a parameter to the remote script and the database is queried using this id to return the contacts that work for that company.

This is my page:

<p>
    <label>Company Name</label>
    <?php echo SelectBuilder::getDirectoryCompany('companylist', '', 'test') ?>
</p>

<p>
    <label>Columnist Name</label>
    <?php echo SelectBuilder::getDirectoryCompanyStaff('directorystaff_id', $companyId, $objectStaffId, 'test1') ?>
</p>

This is the script:

<script>
    $('#test').change(function() {
            var companyId = $(this).val();
            console.log(companyId);// <---  Pass this to the ajax page as a parameter
            $('#test1').load('pages/ajax/company_dropdown.php', {var1: companyId});
    });
</script>

For the most part it works fine. I can call the file, pass the company id as a parameter and output the company id as the option in a select box. However I am trying to populate the select box with the first name and last name of all contacts that work for that company.

Currently I am getting this error:

 Fatal error: Call to a member function query() on a non-object in C:\wamp\www\xxx.tld\pages\ajax\company_dropdown.php on line 12
Regent
  • 5,142
  • 3
  • 21
  • 35
Javacadabra
  • 5,578
  • 15
  • 84
  • 152
  • 2
    This is the wrong line: `$result = $db->query($query);`have you tried to do `var_dump($db);`. It seems like even after having called `global $db` it has no value. Maybe it is not the right variable name. – Valentin Mercier Jul 21 '14 at 10:55
  • 3
    Always prepare user input! http://php.net/manual/en/pdo.prepare.php – Artemkller545 Jul 21 '14 at 10:56
  • Possible duplicate of [Fatal error: Call to a member function ... on a non-object](http://stackoverflow.com/a/12769983/3361444) – Debflav Jul 21 '14 at 10:56
  • @ValentinMercier just did a `var_dump` on the `$db` variable, it would appear it is being set to `null`. I will try to address this situation. – Javacadabra Jul 21 '14 at 10:58

1 Answers1

0

In the end the problem was very simple I forgot to include the file that actually initializes the connection to the database. Once this was done I modified the way I was looping through my results and it worked fine.

Javacadabra
  • 5,578
  • 15
  • 84
  • 152