Jump to content

Not so constant CONSTANTS


TechnoDiver

Recommended Posts

I've been working on a registration form and it seems like the better I get at solving more complex issues the smaller issues plague me the most.

I've got the following function:

//process database actions
function process_database($post) {
  global $table;

  //connect to database
  $connect_db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

  //check database connection
  if ($connect_db->connect_error) {
    return false;
  } else {
    if ($stmt = $connect_db->prepare( "INSERT INTO $table (firstname, lastname, username, email, password) VALUES ( ?, ?, ?, ?, ? )" ) ) {
      $stmt->bind_param(NULL, $firstname, $lastname, $username, $email, $password);

      $firstname = $post['firstname'];
      $lastname = $post['lastname'];
      $username = $post['username'];
      $email = $post['email'];
      $password = $post['password'];

      if (!$stmt->execute()) {
        return false;
      }
    } 
  }

  return true;
}

This is in a functions.php file. The issue is in the $connect_db assignment that has the constants from the config.php file in it.

That file looks like this:

<?php
ob_start();
session_start();

$timezone = date_default_timezone_set("America/xxxxxxx");

$whitelist = array('username', 'email', 'email2', 'password', 'password2');
//TODO here I've removed firstname and lastname from the whitelist as they're optional
//may add them back and try to iterate around them in the future

$table = 'users';

define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'means');

$conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if($conn->connect_errno) {

    printf("Connect Failed: %s\n", $conn->connect_error);
    exit();
    
}

ob_end_flush();
?>

The constants defined in config.php are not being recognized in functions.php. I understand that constants are global and available throughout a script.

I've connected to two files with the following line:

//require config file
require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php');

as I have the config/config.php outside htdocs. I know this works because of a db query to check uniqueness of username that works properly.

Why are these constants coming back as undefined in the process_database().function.php? Nothing I've tried works and I've run out of ideas. TIA

Link to comment
Share on other sites

It's unclear to me how your code is structured, but you need to be sure you're loading each of the files and defining the constants before trying to use them.   So if you had page.php that was trying to use your function, you'd structure it such as:

<?php

require '../config/config.php';
require 'functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
    process_database($_POST);
}

//...

Include the config file first so the constants get defined.  Include the functions file to define your functions, then call your function where needed.

 

Link to comment
Share on other sites

1 hour ago, TechnoDiver said:

The constants defined in config.php are not being recognized in functions.php.

what makes you think that?

since you are making a database connection in config.php, why are you making another one inside the process_database() function? making a database connection is one of the slowest operations you can do on a page. you are doing it at least twice.

Link to comment
Share on other sites

Kicken - thanks for your response.

I've made the calls on register.php like this:

<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); ?>
<?php require_once( 'assets/functions.php' );

at the top of functions.php I have this:

//show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

//require config file
require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php');

my config.php looks as it did in my OP and is located in the same directory as htdocs (research told me it's best to keep it outside the project) and I know that path works as I have another function in functions.php that queries the db for identical usernames and that function works as expected.

the site structure is set up like this:
 

Quote

 

HTDOCS/SITENAME

|- assets

|-loginphp

      | -- assets

            |--- functions.php

     |-- irrelevant directory

     |-- includes

     |-- register.php

|- irrelevant directory

| - another irrelevant directory

| - index.php

 

everything happening in this script is happening inside the loginphp directory except for config/config.php is outside htdocs

Link to comment
Share on other sites

2 minutes ago, mac_gyver said:

what makes you think that?

since you are making a database connection in config.php, why are you making another one inside the process_database() function? making a database connection is one of the slowest operations you can do on a page. you are doing it at least twice.

l think it's not recognizing them because there's red error messages all over them saying they're undefined. I use VSCodium and it doesn't let you save the file for running with critical errors

This is what the intellphense on VSCodium says on the hover over in function.php:

Quote

Undefined constant 'DB_USERNAME'.intelephense(1011)

but it says that for them all, this is just the one I hovered over for the example

Regarding the dual connection - I was just going over it all again and noticed this might be the issue, I see what you're saying. I'll fix it, is it the issue with my constants or is this a separate thing?

Link to comment
Share on other sites

12 minutes ago, mac_gyver said:

^ this is the problem. it apparently doesn't know that the point of constants are that they are global.

What? This is normal behaviour in VScodium? Even with the require() of the config.php file that contains their assignment? Even with intelliphense and all the other PHP extensions I'm using?

How do I fix it? Is there a fix?

Edited by TechnoDiver
added more
Link to comment
Share on other sites

Ha! yea, I started to after that stray colon and then decided that I hadn't really "fixed" anything.

MacGyver had pointed out that I had connected to the db twice, so I rewrote the code eliminating the constants in functions.php

The code you just helped me with in the other thread is the rewrite of the code I posted in my OP here. Because it turned out to be sloppy coding I focused on that and never really got around to figure out how to get VSCodium to recognize them globally

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.