Database constants don't seem to work

Hi Guys. I was browsing the Internet trying to solve my problem and finally I got to here. I have constants.php where I define my DB server, user, password and name, also I have connection.php where I parse these values.
constants.php

// Database Constants
	define("DB_SERVER", "localhost");
	define("DB_USER", "root");
	define("DB_PASS", "root");
	define("DB_NAME", "widget_corp"); 

connection.php

require("constants.php");
	// 1. Create a database connection
	$connection = mysql_connect("DB_SERVER", "DB_USER", "DB_PASS");
	if (!$connection) {
		die("Database connection failed: " . mysql_error());
	}

	// 2. Select a database to use
	$db_select = mysql_select_db("DB_NAME", $connection);
	if (!$db_select) {
		die("Database connection failed: " . mysql_error());
	}

content.php


<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/header.php"); ?>
<section id="sidebar">
	<nav id="navigation">
		<ul class="subjects">
			<?php 
				
				$query = "SELECT * 
				FROM subjects 
				ORDER BY position ASC";
		$subject_set = mysql_query($query, $connection);
		confirm_query($subject_set);
				
				while ($subject = mysql_fetch_array($subject_set)) {
					echo "<li>{$subject["menu_name"]}</li>";

					$query = "SELECT * 
				FROM pages 
				WHERE subject_id = {$subject["id"]} 
				ORDER BY position ASC";
		$page_set = mysql_query($query, $connection);
		confirm_query($page_set);

					echo "<ul class=\\"pages\\">";
					while ($page = mysql_fetch_array($page_set)) {
						echo "<li>{$page["menu_name"]}</li>";
					}
					echo "</ul>";
				}

			 ?>
		 </ul>
	</nav>
</section>
<section id="page">
	<h2>Content Area</h2>
	
</section>
<?php require("includes/footer.php"); ?>

After I run my code I receive this error
Database connection failed: Unknown MySQL server host ‘DB_SERVER’ (2)

If I change all the variables in connection.php with their values it works fine. I use MAMP. Thank you.

You don’t use quotes when you use define

$connection = mysql_connect("DB_SERVER", "DB_USER", "DB_PASS");

Should be

$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);

Thanks cpradio, that is working well now. However I have another problem. In content.php if I make a function out of query for subjects in functions.php I have Database connection failed: as a result.
If I take this bit

$query = "SELECT *
                FROM subjects
                ORDER BY position ASC";
        $subject_set = mysql_query($query, $connection);
        confirm_query($subject_set);

and replace it with

$subject_set = get_all_subjects();

content.php

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/header.php"); ?>
<section id="sidebar">
	<nav id="navigation">
		<ul class="subjects">
			<?php
                        $subject_set = get_all_subjects();
                        while ($subject = mysql_fetch_array($subject_set)) {
                                echo "<li>{$subject["menu_name"]}</li>";

                                $query = "SELECT *
                        FROM pages
                        WHERE subject_id = {$subject["id"]}
                        ORDER BY position ASC";
                        $page_set = mysql_query($query, $connection);
                        confirm_query($page_set);

                                                echo "<ul class=\\"pages\\">";
                                                while ($page = mysql_fetch_array($page_set)) {
                                                        echo "<li>{$page["menu_name"]}</li>";
                                                }
                                                echo "</ul>";
                                        }

			 ?>
		 </ul>
	</nav>
</section>
<section id="page">
	<h2>Content Area</h2>
	
</section>
<?php require("includes/footer.php"); ?>

I have an error

functions.php

function get_all_subjects() {
		$query = "SELECT *
                        FROM subjects
                        ORDER BY position ASC";
		$subject_set = mysql_query($query, $connection);
		confirm_query($subject_set);
		return $subject_set;
	}

If I had to guess, maybe because of this:

$db_select = mysql_select_db("DB_NAME", $connection);

Did you update “DB_NAME” to be DB_NAME too?

Yes, I did. NetBeans shows a warning in functions.php

$subject_set = mysql_query($query, $connection);

Variable $connection seems to be uninitialazied.

Okay, here is the problem, your $connection variable isn’t accessible in get_all_subjects(). You have two options, one you can give it scope, or two, you can pass it to your get_all_subjects() function.

Giving it Scope:

function get_all_subjects() {
		global $connection;
		$query = "SELECT * 
                        FROM subjects 
                        ORDER BY position ASC";
		$subject_set = mysql_query($query, $connection);
		confirm_query($subject_set); 
		return $subject_set;
	}

Passing it to the Function:

function get_all_subjects($connection) {
		$query = "SELECT * 
                        FROM subjects 
                        ORDER BY position ASC";
		$subject_set = mysql_query($query, $connection);
		confirm_query($subject_set); 
		return $subject_set;
	}

Then in content.php

$subject_set = get_all_subjects($connection);

Since you are doing procedural programming, I’d probably lean towards using the global keyword, but if you ever want to get into OOP, you will find that passing your connection around is a much better process from a testing standpoint.

Yes, it is definitely working. I used passing option for subjects, but what about pages for a subject, I passed $subject_id already. What would I have to do if I needed to pass $connection as well, would I just add a second attribute like that ($subject[“id”], $connection)?

Correct, you just pass a second argument :slight_smile:

Thank you for your time. That was very useful.

Hello again,

I have a new problem with my redirect function. Although it seems fine it doen’s redirect.

new_subject.php

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php find_selected_page($connection); ?>
<?php include("includes/header.php"); ?>
<section id="sidebar">
	<nav id="navigation">
            <?php echo navigation($sel_subject,$sel_page,$connection); ?>

            <a class="new-subject" href="new_subject.php" title="Add a new subject">+ Add a new subject</a>

	</nav>
</section>
<section id="page">
    <h2>Add Subject</h2>

    <form action="create_subject.php" method="post">
        <ul class="subject-name">
            <li><label>Subject name:</label></li>
            <li><input type="text" name="menu_name" value="" id="menu_name" /></li>
        </ul>
        <div class="position">Position
            <select name="position">
                <?php
                    $subject_set = get_all_subjects($connection);
                    $subject_count = mysql_num_rows($subject_set);
                    for($count=1; $count <= $subject_count+1; $count++) {
                        echo "<option value=\\"{$count}\\">{$count}</option>";
                    }
                ?>
            </select>
        </div>
        <ul class="visibility clearfix">
            <li class="label">Visible</li>
            <li class="no"><input type="radio" name="visible" value="0" />No</li>
            <li class="yes"><input type="radio" name="visible" value="1" />Yes</li>
        </ul>
        <input class="subject-submit" type="submit" value="Add Subject" />
    </form>

    <a href="content.php">Cancel</a>

</section>
<?php require("includes/footer.php"); ?>

create_subject.php

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
    $errors = array();

    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }

?>
<?php
    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);
?>

<?php
    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }
?>

<?php mysql_close($connection); ?>

function.php

function redirect_to($location = NULL) {
            if ($location != NULL) {
                header("Location: {$location}");
                exit;
            }
        }

So I am doing form validation. If the form field is empty then it should redirect me to new_subject.php, but it sends me create_redirect.php instead. Maybe it doesn’t redirect because any error wan’t found. I added header redirect code from my function.php only, otherwise there will be lots of code here.

It might be because it is early in the morning and I’m not 100% awake yet, but I don’t see any errors within your code. The first thing I would check is you apache logs for an error, something along the lines of “Cannot modify header information - headers already sent by …”

If you see that warning/error, you will need to make sure there is ZERO whitespace above your opening PHP tag in create_subject.php and ZERO whitespace after your closing PHP tag.

Thank you for your quick reply. I have the following error in php log actually
PHP Warning: Cannot modify header information - headers already sent by (functions.php:128) in functions.php on line 24

YOu mean I should have a ZERO space before <?php require_once(“includes/connection.php”); ?> and after <?php mysql_close($connection); ?>, which are at the beginning and at the end of the page?


<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
    $errors = array();

    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }

?>
<?php
    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);
?>

<?php
    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }
?>

<?php mysql_close($connection); ?>

Yes, and there should be ZERO spaces above any opening and after any closing tags within those files too for the error to go away. Another option you have is to include those files AFTER validation
like so


<?php     
    $errors = array();
    
    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }    
    
?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);
?>
<?php
    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }
?>
<?php mysql_close($connection); ?>

Non of the options worked. First I tried this


<?php require_once("includes/connection.php"); ?>

<?php require_once("includes/functions.php"); ?>

<?php
    $errors = array();

    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }

?>

<?php
    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);
?>

<?php
    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }
?>

<?php mysql_close($connection); ?>

then this


<?php
    $errors = array();

    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }

?>

<?php require_once("includes/connection.php"); ?>

<?php require_once("includes/functions.php"); ?>

<?php
    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);
?>

<?php
    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }
?>

<?php mysql_close($connection); ?>

Same thing, redirect to create_page.

It is the whitespacing, you can’t have it when using header().

<?php     
    $errors = array();
    
    // Form Validation

    if (!isset($_POST['menu_name']) || empty($_POST['menu_name'])) {
        $errors[] = 'menu_name';
    }

    if (!empty($errors)) {
        redirect_to("new_subject.php");
    }    
    
    require_once("includes/connection.php"); // make sure there is no whitespace in this file too!
    require_once("includes/functions.php"); // make sure there is no whitespace in this file too!

    $menu_name = mysql_prep($_POST['menu_name']);
    $position = mysql_prep($_POST['position']);
    $visible = mysql_prep($_POST['visible']);

    $query = "INSERT INTO subjects (
        menu_name, position, visible
        ) VALUES (
        '{$menu_name}', {$position}, {$visible}
        )";
    $result = mysql_query($query, $connection);
    if ($result) {
        // Success!
        redirect_to("content.php");
    } else {
        // Display error message.
        echo "<p>Subject creation failed.</p>";
        echo "<p>" . mysql_error() . "</p>";
    }

    mysql_close($connection); 
?>

A… So ZERO whitespace means no whitespace? I though it’s other way round. Let me see…

Sorry, I should have been clearer on that :slight_smile: At least we are working in the right direction now :smiley:

It is working! I checked and removed all whitespaces before and after php tag from: functions.php and connections.php, also I removed all whitespaces in create_subject.php and new_subject.php. It is something you won’t find in tutorials. THank you for your cooperation. :slight_smile: