Is it not possible to include mysql query in an included php file?

I am attempting to place my mysql query and fetch code in an included file. However, when I tried to do this, the main page (which included the mysql code) started throwing errors that it did not recognize any of the variables that should have been defined in the included file. Is there any reason why this would be happening?

Off the top of my head I’d say it’s the path to DB connection.

How so?
connect.php:

$host = 'localhost'; $user = ''; $password = ''; $db = '';
page.php:

[code]include_once(‘connect.php’);
$connection = mysqli_connect($host, $user, $password, $db) or die();
mysqli_select_db($connection, $db);

// Build list of products
$products_SQL = mysqli_query($connection, “SELECT category, shortname, brand, product, price, price_prefix, price_suffix FROM compare_wearables ORDER BY brand, product”) or die(mysqli_error($connection));
$products = array();
$categories = array();
$acceptable_productNames = array();
$acceptable_productShortnames = array();
$categoryForShortname = array();
while($product = mysqli_fetch_assoc($products_SQL)) {
$products = $product;
$categories = $product[‘category’];
$acceptable_productNames[$product[‘shortname’]] = $product[‘brand’] . ’ ’ . $product[‘product’];
$acceptable_productShortnames = $product[‘shortname’];
$categoryForShortname[$product[‘shortname’]] = $product[‘category’];
}
$categories = array_unique($categories);

// Close connection
mysqli_close($connection);[/code]

What I do is I have a file structure like the following
lib/css
lib/includes
lib/includes/connect
lib/images
lib/js
lib/classes

For example this would be in lib/includes/connect as db_connect.php

   <?php
    /* Setup database constants */
    define('DATABASE_HOST', 'localhost'); // Host Name
    define('DATABASE_NAME', 'name_of_database'); // Database Name
    define('DATABASE_USERNAME', 'username'); // Username
    define('DATABASE_PASSWORD', 'password'); // Password

Then in your example I would do the following:

<?php
require_once 'lib/includes/connect/db_connect.php';
$connection = mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME) or die();

This is just an example and I like using CONSTANTS instead of variables, for you are pretty sure they will stay constant (no pun intended). Actually you could probably put the above in a config.php or utilities.inc.php file put it in the lib/includes folder with the following change:

require_once 'connect/db_connect.php';

Again this is just an example and everyone has a different way in setting up their folders and files. HTH

Is that the full code of your include file? If so, you need opening and closing PHP tags. From the documentation at http://php.net/manual/en/function.include.php :

“When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.”

the end tag at the end of an include can be omitted - this can avoid hard to find errors caused by any space after the closing tag.

Yes, I am including my php tags.

I get errors like this:

[quote]Warning: Invalid argument supplied for foreach() in /home3/jes269/public_html/v2/select.php on line 58
[/quote]

Line 58 is

foreach($categories as $category) {

Is the code and query sample from post#4 included on select.php? You defined $categories = array(); so even if the query returned no results the foreach line shouldn’t throw errors.

What does select.php look like?

I wonder if it’s an include_once() VS include() issue.

I wonder what array_unique returns if passed an empty array.

Maybe try commenting out that line and see what happens?

I think there’s a bit of a misunderstanding, here. The code works perfectly when it’s on one page. When i move part of the code into an included file, however, I get the errors.

I want to move this part into connect.php, which currently has my login credentials.

// Build list of products

[code]<?php

include_once(‘header.php’);

// Connect to database
include_once(‘connect.php’);
$connection = mysqli_connect($host, $user, $password, $db) or die();
mysqli_select_db($connection, $db);

// Build list of products
$products_SQL = mysqli_query($connection, “SELECT category, shortname, brand, product, price, price_prefix, price_suffix FROM compare_wearables ORDER BY brand, product”) or die(mysqli_error($connection));
$products = array();
$categories = array();
$brands = array();
$acceptable_productNames = array();
$acceptable_productShortnames = array();
$categoryForShortname = array();
while($product = mysqli_fetch_assoc($products_SQL)) {
$products = $product;
$categories = $product[‘category’];
$brands = $product[‘brand’];
$acceptable_productNames[$product[‘shortname’]] = $product[‘brand’] . ’ ’ . $product[‘product’];
$acceptable_productShortnames = $product[‘shortname’];
$categoryForShortname[$product[‘shortname’]] = $product[‘category’];
}
$categories = array_unique($categories);
$brands_unique = array_unique($brands);

// Close connection
mysqli_close($connection);

?>

<?php // Categories foreach($categories as $category) { ?>
<div class="category">
	<div class="category-heading">
		Compare <strong><?= $category ?></strong><span class="category-add"></span>
	</div>

	<ul class="products" id="<?= str_replace(" ", "", $category) ?>">

	<?
	// Products
	foreach($products as $option) {
		if($option['category'] == $category) { ?>
		
			<li>
				<input type="checkbox" name="vs" value="<?php echo $option['shortname']; ?>" id="<?= $option['shortname'] ?>">
				<label for="<?php echo $option['shortname']; ?>">
					<img src="/images/compare-<?= $option['shortname'] ?>.jpg" alt="<?= $option['shortname'] ?>">
					<div>
						<span class="brand"><?= $option['brand'] ?></span>
						<span class="product"><?= $option['product'] ?></span>
						<span class="price"><?php echo $option['price_prefix'] . '$' . $option['price']; ?></span>
					</div>
				</label>
			</li> <?php
		}
	} ?>

	</ul>

</div>
		<div class="submit-compare"><label for="submit-compare" class="sB medium blue round bold upper fa-right">Compare selections<i class="fa fa-arrow-circle-right"></i></label></div>

<?php

}

?>

Or Select a Popular Comparison
<?php
$brands_count = array_count_values($brands);
foreach($brands_unique as $brand) {
	if ($brands_count[$brand] > 1) {
		$brand_lowercase = strtolower($brand);
		?>

		<span class="like-products" class="PopularComparisons">	
			<div class="like-li">
				<div class="like-label">
					<img src="/images/compare-folder.png" alt="<?= $brand ?>">
					<div class="like-div">
						<span class="like-brand">All</span>
						<span class="like-product"><?= $brand ?></span>
						<span class="like-price"><?= $brands_count[$brand] ?> wearables</span>
					</div>
				</div>
			</div> 			
		</span>

		<?php
	}
}
?>
<?php include_once('footer.php'); ?>[/code]

I don’t see anything wrong with having any number of queries in an included file. So you should be able to have connect.php like so.

<?php 
$host = 'localhost';
$user = '';
$password = '';
$db = '';
$connection = mysqli_connect($host, $user, $password, $db) or die();
mysqli_select_db($connection, $db);
// Build list of products
$products_SQL = mysqli_query($connection, "SELECT category, shortname, brand, product, price, price_prefix, price_suffix FROM compare_wearables ORDER BY brand, product") or die(mysqli_error($connection));
$products = array();
$categories = array();
$brands = array();
$acceptable_productNames = array();
$acceptable_productShortnames = array();
$categoryForShortname = array();
while($product = mysqli_fetch_assoc($products_SQL)) {
    $products[] = $product;
    $categories[] = $product['category'];
    $brands[] = $product['brand'];
    $acceptable_productNames[$product['shortname']] = $product['brand'] . ' ' . $product['product'];
    $acceptable_productShortnames[] = $product['shortname'];
    $categoryForShortname[$product['shortname']] = $product['category'];
}
$categories = array_unique($categories);
$brands_unique = array_unique($brands);
// Close connection
mysqli_close($connection);

?>

Then any page based on your example have

<?php
include_once('header.php');
// Connect to database
include_once('connect.php');
?>
<!--<div class="tags">
    <a href="#" class="sB tiny lightblue bold height round">Fitbit</a>
    <a href="#" class="sB tiny lightblue bold height round">Garmin</a>
    <a href="#" class="sB tiny lightblue bold height round">Jawbone</a>
    <a href="#" class="sB tiny lightblue bold height round">LG</a>
    <a href="#" class="sB tiny lightblue bold height round">Misfit</a>
    <a href="#" class="sB tiny lightblue bold height round">Motorola</a>
    <a href="#" class="sB tiny lightblue bold height round">Pebble</a>
    <a href="#" class="sB tiny lightblue bold height round">Samsung</a>
    <a href="#" class="sB tiny lightblue bold height round">Sony</a>
    <a href="#" class="sB tiny lightblue bold height round">Withings</a>
    <a href="#" class="sB tiny lightblue bold height round">Smartwatches</a>
    <a href="#" class="sB tiny lightblue bold height round">Fitness&nbsp;Bands</a>
    <a href="#" class="sB tiny lightblue bold height round">Basic&nbsp;Activity&nbsp;Trackers</a>
</div>-->
<div class="container-columns">
    <div class="select-textbox">
        <span class="select-text">
            <!--<strong>Design your own wearables comparison by selecting up to 6 wearables.</strong>
            Alternatively, you can choose from one of our <a href="#">popular comparisons</a>.
            If you'd like to compare a wearable that does not already appear in our collection, <a href="#">let us know</a>.-->
        </span>
    </div>
    <div class="select-share">
        <a href="https://www.facebook.com/dialog/share?app_id=145634995501895&display=popup&href=<?= $thisURL ?>&redirect_uri=<?= $thisURL ?>" class="sB facebook xsmall round block"><i class="fa fa-facebook"></i><span class="min480">Share<span class="min640"> on <strong>Facebook</strong></span></span></a>
        <a href="https://twitter.com/share" data-via="comparewear" data-count="none" class="sB twitter xsmall round block"><i class="fa fa-twitter"></i><span class="min480">Share<span class="min640"> on <strong>Twitter</strong></span></span></a>
            <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
        <a href="https://plus.google.com/share?url=<?= $thisURL ?>" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;" class="sB google xsmall round block"><i class="fa fa-google"></i><span class="min480">Share<span class="min640"> on <strong>Google&plus;</strong></span></span></a>
        <a href="mailto:?subject=Compare Wearables&amp;body=<?= $thisURL ?>" class="sB gray xsmall round block"><i class="fa fa-envelope"></i><span class="min480">Email</span></a>
    </div>
</div>
<form action="compare.php" method="GET">
    <input type="submit" id="submit-compare">
<script>
jQuery(function(){
    var max = 6;
    var checkboxes = $('.products input[type="checkbox"]');                 
    checkboxes.change(function() {
        var current = checkboxes.filter(':checked').length;
        checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
    });
});
</script>
<?php
// Categories
foreach($categories as $category) { ?>
    <div class="category">
        <div class="category-heading">
            Compare <strong><?= $category ?></strong><span class="category-add"></span>
        </div>
        <ul class="products" id="<?= str_replace(" ", "", $category) ?>">
        <?
        // Products
        foreach($products as $option) {
            if($option['category'] == $category) { ?>
                <li>
                    <input type="checkbox" name="vs" value="<?php echo $option['shortname']; ?>" id="<?= $option['shortname'] ?>">
                    <label for="<?php echo $option['shortname']; ?>">
                        <img src="/images/compare-<?= $option['shortname'] ?>.jpg" alt="<?= $option['shortname'] ?>">
                        <div>
                            <span class="brand"><?= $option['brand'] ?></span>
                            <span class="product"><?= $option['product'] ?></span>
                            <span class="price"><?php echo $option['price_prefix'] . '$' . $option['price']; ?></span>
                        </div>
                    </label>
                </li> <?php
            }
        } ?>
        </ul>
    </div>
            <div class="submit-compare"><label for="submit-compare" class="sB medium blue round bold upper fa-right">Compare selections<i class="fa fa-arrow-circle-right"></i></label></div>
    <?php
}
?>
<div class="category">
    <div class="category-heading">
        Or Select a <strong>Popular Comparison</strong>
    </div>
    <?php
    $brands_count = array_count_values($brands);
    foreach($brands_unique as $brand) {
        if ($brands_count[$brand] > 1) {
            $brand_lowercase = strtolower($brand);
            ?>
            <span class="like-products" class="PopularComparisons">    
                <div class="like-li">
                    <div class="like-label">
                        <img src="/images/compare-folder.png" alt="<?= $brand ?>">
                        <div class="like-div">
                            <span class="like-brand">All</span>
                            <span class="like-product"><?= $brand ?></span>
                            <span class="like-price"><?= $brands_count[$brand] ?> wearables</span>
                        </div>
                    </div>
                </div>             
            </span>
            <?php
        }
    }
    ?>
</div>
</form>
<?php include_once('footer.php'); ?>

I often have an includes.php file that has any number of common queries and functions.

I don’t see the problem either, except that there is one. That’s why I posted!

I see you have a short tag above the products foreach and at least on my test server <?= doesn’t work. Maybe you need error reporting on. This is my revised version, which worked after making these changes.

<?php
include_once('header.php');
// Connect to database
include_once('connect.php');
?>
<!--<div class="tags">
    <a href="#" class="sB tiny lightblue bold height round">Fitbit</a>
    <a href="#" class="sB tiny lightblue bold height round">Garmin</a>
    <a href="#" class="sB tiny lightblue bold height round">Jawbone</a>
    <a href="#" class="sB tiny lightblue bold height round">LG</a>
    <a href="#" class="sB tiny lightblue bold height round">Misfit</a>
    <a href="#" class="sB tiny lightblue bold height round">Motorola</a>
    <a href="#" class="sB tiny lightblue bold height round">Pebble</a>
    <a href="#" class="sB tiny lightblue bold height round">Samsung</a>
    <a href="#" class="sB tiny lightblue bold height round">Sony</a>
    <a href="#" class="sB tiny lightblue bold height round">Withings</a>
    <a href="#" class="sB tiny lightblue bold height round">Smartwatches</a>
    <a href="#" class="sB tiny lightblue bold height round">Fitness&nbsp;Bands</a>
    <a href="#" class="sB tiny lightblue bold height round">Basic&nbsp;Activity&nbsp;Trackers</a>
</div>-->
<div class="container-columns">
    <div class="select-textbox">
        <span class="select-text">
            <!--<strong>Design your own wearables comparison by selecting up to 6 wearables.</strong>
            Alternatively, you can choose from one of our <a href="#">popular comparisons</a>.
            If you'd like to compare a wearable that does not already appear in our collection, <a href="#">let us know</a>.-->
        </span>
    </div>
    <div class="select-share">
        <a href="https://www.facebook.com/dialog/share?app_id=145634995501895&display=popup&href=<?php echo $thisURL; ?>&redirect_uri=<?php echo $thisURL; ?>" class="sB facebook xsmall round block"><i class="fa fa-facebook"></i><span class="min480">Share<span class="min640"> on <strong>Facebook</strong></span></span></a>
        <a href="https://twitter.com/share" data-via="comparewear" data-count="none" class="sB twitter xsmall round block"><i class="fa fa-twitter"></i><span class="min480">Share<span class="min640"> on <strong>Twitter</strong></span></span></a>
            <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
        <a href="https://plus.google.com/share?url=<?php echo $thisURL; ?>" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;" class="sB google xsmall round block"><i class="fa fa-google"></i><span class="min480">Share<span class="min640"> on <strong>Google&plus;</strong></span></span></a>
        <a href="mailto:?subject=Compare Wearables&amp;body=<?php echo $thisURL; ?>" class="sB gray xsmall round block"><i class="fa fa-envelope"></i><span class="min480">Email</span></a>
    </div>
</div>
<form action="compare.php" method="GET">
    <input type="submit" id="submit-compare">
<script>
jQuery(function(){
    var max = 6;
    var checkboxes = $('.products input[type="checkbox"]');                 
    checkboxes.change(function() {
        var current = checkboxes.filter(':checked').length;
        checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
    });
});
</script>
<?php
// Categories
foreach($categories as $category) { ?>
    <div class="category">
        <div class="category-heading">
            Compare <strong><?php echo $category; ?></strong><span class="category-add"></span>
        </div>
        <ul class="products" id="<?php echo str_replace(" ", "", $category); ?>">
        <?php
        // Products
        foreach($products as $option) {
            if($option['category'] == $category) { ?>
                <li>
                    <input type="checkbox" name="vs" value="<?php echo $option['shortname']; ?>" id="<?php echo $option['shortname']; ?>">
                    <label for="<?php echo $option['shortname']; ?>">
                        <img src="/images/compare-<?php echo $option['shortname']; ?>.jpg" alt="<?php echo $option['shortname']; ?>">
                        <div>
                            <span class="brand"><?php echo $option['brand']; ?></span>
                            <span class="product"><?php echo $option['product']; ?></span>
                            <span class="price"><?php echo $option['price_prefix'] . '$' . $option['price']; ?></span>
                        </div>
                    </label>
                </li> <?php
            }
        } ?>
        </ul>
    </div>
            <div class="submit-compare"><label for="submit-compare" class="sB medium blue round bold upper fa-right">Compare selections<i class="fa fa-arrow-circle-right"></i></label></div>
    <?php
}
?>
<div class="category">
    <div class="category-heading">
        Or Select a <strong>Popular Comparison</strong>
    </div>
    <?php
    $brands_count = array_count_values($brands);
    foreach($brands_unique as $brand) {
        if ($brands_count[$brand] > 1) {
            $brand_lowercase = strtolower($brand);
            ?>
            <span class="like-products" class="PopularComparisons">    
                <div class="like-li">
                    <div class="like-label">
                        <img src="/images/compare-folder.png" alt="<?php echo $brand; ?>">
                        <div class="like-div">
                            <span class="like-brand">All</span>
                            <span class="like-product"><?php echo $brand; ?></span>
                            <span class="like-price"><?php echo $brands_count[$brand]; ?> wearables</span>
                        </div>
                    </div>
                </div>             
            </span>
            <?php
        }
    }
    ?>
</div>
</form>
<?php include_once('footer.php'); ?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.