How to use a Php constant with an array element

I am in the process of writing a demo which shows source files and requires database access.

I managed to solve the problem of not publishing my database login details but convince there must be a better way.

 // Database Access Details
    $docRoot    = $_SERVER['DOCUMENT_ROOT'];
    $lastPath   = strrchr($docRoot, '/');
    $aboveRoot  = str_replace($lastPath, '/', $docRoot);
    $aboveRoot .= '_dbPARAMS.php';
    if( file_exists($aboveRoot) ):
      require $aboveRoot;
      define('HOST',  'yourhost');
      define('uName', 'userName');
      define('pWORD', 'passWord');  
      define('dBase', 'dataBase'); 
      define('dTABLE', 'tableName'); 
      define('dCOLUMN','columnName');  // SEE KLUDGE BELOW

$conn =  mysqli_connect(HOST, uNAME, pWORD, dBASE);
$sql  = 'SELECT * FROM ' .dTABLE .' WHERE ';// .dCOLUMN; 

  foreach($aParams as $i2 => $param):
    if($i2 > 0):
      $sql = $sql .' AND ';
    $sql = $sql .dCOLUMN .' LIKE "%'. trim($param) .'%" ';

// all the constants work except dCOLUMN
   $dCOLUMN = dCOLUMN; // KLUDGE constant to string!!!
   while($row = mysqli_fetch_array($result))
       echo '<br />' . $row["$dCOLUMN"];// see KLUDGE above

Hmmm. I wonder if it’s because you are not following the CONSTANT naming convention.

AFAIK there is no rule that CONSTANTs need to be all uppercase so I would think dCOLUMN is valid.

PHP “fixes” code that has associative array string literal keys that are not inside quotation marks

According to the documentation

PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string ‘bar’ and use that.

Because you need a kludge, it looks like PHP is not recognizing dCOLUMN as “known symbol”.

1 Like

Why don’t you use it like this?

 echo '<br />' . $row[dCOLUMN]; //use constant directly
1 Like

Many thanks.

Now I understand.

I thought it was essential to have a quoted “string”.

Many thanks, it works a treat.

The nearly completed Ajax Search Routine Tutorial

Only the last 5% left to do :slight_smile:

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