Functions not working... probably simple reason?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
speckytwat
New php-forum User
New php-forum User
Posts: 9
Joined: Tue Sep 05, 2017 12:33 am

Mon Sep 11, 2017 7:22 am

Hi, I've been trying to set up functions to tidy up code in a project and avoid repetition for some things. One of those things is a simple database query that just fetches a list of company names.

It works fine when put inside a SELECT in a form, as follows:

Code: Select all

<label for="_Exhibitor1">Exhibitor 1</label>
        <select name="_Exhibitor1" size="1">
        <option selected value="">&nbsp;</option>
        <?php
        $getexhibitor = $conn->query("SELECT * FROM exhibitors WHERE Status NOT LIKE 'Archived'");
	  			while ($row = $getexhibitor->fetch_assoc()) { 
					echo '<option value="'.$row["CompanyName"].'">'.$row["CompanyName"].'</option>';
					$count++;
					}
	  ?>
	    </select>

So I decided to put the PHP section into a reusable function as I will use this quite a few times.

I created a functions.php file and in my main page (where the form is), I put an include:

Code: Select all

include ('include/functions.php');
And inside functions.php I put:

Code: Select all

<?php
include ('dbconnect.php');
function GetExhibitorList() {
	$getexhibitor = $conn->query('SELECT * FROM exhibitors WHERE Status NOT LIKE "Archived"');
	  			while ($row = $getexhibitor->fetch_assoc()) { 
					echo '<option value="'.$row["CompanyName"].'">'.$row["CompanyName"].'</option>';
					$count++;
					}
}

?>
The PHP works fine if put directly in the SELECT, but obviously I want to just call the function instead, like so:

Code: Select all

<label for="_Exhibitor1">Exhibitor 1</label>
        <select name="_Exhibitor1" size="1">
        <option selected value="">&nbsp;</option>
        <?php GetExhibitorList(); ?>
	    </select>
But instead of outputting the list from the database, it outputs nothing (except the first, blank option)

Any ideas? Thanks!

User avatar
hyper
php-forum Active User
php-forum Active User
Posts: 498
Joined: Mon Feb 22, 2016 5:52 pm

Mon Sep 11, 2017 7:57 am

You need it pass the function your database as it isn't global.

This might a case for using Stored Procedures

Also turn on display errors while developing.

speckytwat
New php-forum User
New php-forum User
Posts: 9
Joined: Tue Sep 05, 2017 12:33 am

Mon Sep 11, 2017 8:36 am

Thanks, I did include my database connection script in the functions.php, do I need to do something else?

User avatar
hyper
php-forum Active User
php-forum Active User
Posts: 498
Joined: Mon Feb 22, 2016 5:52 pm

Mon Sep 11, 2017 10:11 am

You need to pass your database connection to your function and turn on error reporting while you are developing.

Post Reply