PHP - Please Help Echoing Constant
Hi,
I'm trying to echo some error message like this: Code: [Select] <?php echo (isset($_GET['failed']))?'.CNT_TXT_MYERRORMESSAGE.''; ?> i know it must be a syntax error....but I'm a newb.... Thanks Similar TutorialsHi, Please can someone tell me why the text in my constant is not displaying? Code: [Select] if($totalRows_checkdup_RS==1) { $errorMsg = '.CNT_TXT_WARNING_EMAILEXISTE.'; // I want this constant to print a warning message but all I get printed is the constant!!! } else{ Can someone help me out, I had a guy make some great changes to a script. works perfectly - however I want to modify it further and he's unavailable till tomorrow to discuss. Hopefully someone will be able to guide me: define('TBL_PROFILE_COUNTRY_FILTER', '`country_id` = \'IE\''); This line is based on users in a database from Ireland (IE) but what I need to do is make it so that this TBL_PROFILE_COUNTRY_FILTER doesnt just filter Ireland members but also those from Northern Ireland (Ni) as well. So my question is this - can I (and if so how) - can I add Ni to this define statement. Grateful for any guidance (php isn't my thing at all but I'm trying to pick up what I need when I need it). Thanks again. I get an undefined constant error message. Am I using the variable correctly? Should I use an echo to output the variable as text? Added by <?php ${displayName}; ?> I can't see what I'm doing wrong here. When I use this code, the link HOME gets echoes with no problem: Code: [Select] <td valign="middle"><?php echo '<a href="index.php"'; if(strstr($checkit,"index.php")) echo ' class="clicked"'; else echo ' class="menulinks"'; echo '>HOME</a>'; ?></td> ...but when I swap HOME with a php constant, I get nothing... Code: [Select] <td valign="middle"><?php echo '<a href="index.php"'; if(strstr($checkit,"index.php")) echo ' class="clicked"'; else echo ' class="menulinks"'; echo '><?=CNT_TXT_HOME?></a>'; ?></td> Please help I am having a problem with some php code that runs on a landing page that queries a database for the content needed to display on the template page from the keywords passed in the url. My issue is that when I tried to add some php code to the template page it reads it fails and returns Notice: Use of undefined constant tdbd_name - assumed 'tdbd_name' in /var/www/ppcindex.php on line 147 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /var/www/ppcindex.php on line 150 If anyone could point me in the right direction it would be much appreciated. Here is the code from the landing page php <?php // template variables - PLEASE CHANGE error_reporting(E_ALL); ini_set('display_errors','On'); define("TEMPLATE_NAME","ppcindexcontent.php"); // your page templates define("FULL_PATH","/var/www/speedppc/"); // true path to your speedPPC install directory define("MAX_ROWS",1); // maximum display rows for CSV data - we recommend no more the 100 records if(!isset($_GET["CSVID"])){ define("CSVID", "18"); // CSVID of your csv file. leave blank if passing csvid in the url (See README.txt) } else { define("CSVID", $_GET[csvid], true); } define("REPLACECHAR", '-'); // this is the replacement character for the custom function replace() // include files include(FULL_PATH."config.php"); include(FULL_PATH."common.php"); // variables passed in URL $csvkeyword = $_GET['csvkeyword']; $seed = $_GET['seed']; $expansion = $_GET['expansion']; $final = $_GET['final']; // connect to DB $dbhandle = dbconnect($host, $user, $pass, $db); // functions function replaceTokens($passedContent) { global $csvkeyword, $seed, $expansion, $final; $tokens = array("[%csvkeyword%]", "[%seed%]", "[%expansion%]", "[%final%]", "[%Csvkeyword%]", "[%Seed%]", "[%Expansion%]", "[%Final%]"); $tokenValues = array(rs($csvkeyword), rs($seed), rs($expansion), rs($final), uc(rs($csvkeyword)), uc(rs($seed)), uc(rs($expansion)), uc(rs($final))); $replacedContent = str_replace($tokens, $tokenValues, $passedContent); return $replacedContent; } function stripUndefinedTokens($passedContent) { $patterns = '/\[%.*?(%\]|\]|%)/'; $result = preg_replace($patterns, '', $passedContent); return $result; } function changeCase($passedContent) { $patterns = '/\$.*?\]/'; $string = $passedContent; preg_match_all($patterns, $string, $matches); $uniqueMatches = array_unique($matches[0]); foreach($uniqueMatches as $key => $value) { if(substr($value, 13, 1) == strtoupper(substr($value, 13, 1))) { $string = str_replace($value, '".ucwords('.strtolower($value).')."', $string); } } return $string; } function replaceChar($passedContent) { $string = $passedContent; $patterns = '/replace\(.*?\)/'; preg_match_all($patterns, $string, $matches); $replaceChar = '-'; foreach($matches[0] as $key => $value) { $valueReplaced = str_replace(' ', REPLACECHAR, $value); $string = str_replace($value, $valueReplaced, $string); } $replace = array("replace(", ")"); //$string = str_replace($replace, '', $string); return $string; } function rs($passWord) { return str_replace('-', ' ', $passWord); } function uc($passWord) { return ucfirst($passWord); } // get CSV table Information $sql = "SELECT * FROM tabledb_details WHERE tdbd_id = '".CSVID."'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); // replace '-' in keyword with space and also use keyword with '-' in it incase it is part of the word $keywordsArray = explode(",", $csvkeyword); $i = 0; foreach($keywordsArray as $key => $value) { $keywords[$i] = $value; $i++; $position = strpos($value, '-'); if($position !== false){ $keywords[$i] = str_replace("-", " ", $value); $i++; } } // CSV fields to search keyword occurence in $keywordFields = explode("|", $row[tdbd_search_fields]); $sqlKeyword = ' ('; foreach($keywords as $key => $value) { $sqlKeyword .= "("; foreach($keywordFields as $keyField => $valueField) { $sqlKeyword .= "`" . $valueField . "` REGEXP '( |^)".$value."( |s|[\.]|$)' OR "; } $sqlKeyword = substr($sqlKeyword, 0, -4); $sqlKeyword .= ") OR "; } $sqlKeyword = substr($sqlKeyword, 0, -4).')'; // set the default sql 'where' section if the keyword is not defined in url if($csvkeyword == '' || !isset($csvkeyword)) { $sqlKeyword = '1'; } // start template Display Output ob_start(); include(TEMPLATE_NAME); $output = ob_get_contents(); ob_end_clean(); // get the position of the loop template $loopStart = strpos($output,"[start_csv_loop]"); $loopEnd = strpos($output,"[end_csv_loop]"); // get the loop template layout $loopTemplate = substr($output, ($loopStart+16), ($loopEnd-($loopStart+16))); // get content before loop template $preContent = stripslashes(stripUndefinedTokens(addslashes(replaceTokens(substr($output, 0, $loopStart))))); // get content after loop template $postContent = stripslashes(stripUndefinedTokens(addslashes(replaceTokens(substr($output, $loopEnd+14))))); // output pre content eval("\$preContent = \"$preContent\";"); print_r( replaceChar($preContent) ); $sqlSearch = "SELECT * FROM ".$row[tdbd_name]." WHERE ".$sqlKeyword." LIMIT ".MAX_ROWS; $resultSearch = mysql_query($sqlSearch); while($displayrows = mysql_fetch_assoc($resultSearch)) { $display = replaceTokens($loopTemplate); $display = str_replace('\\', '[backslash]', $display); $display = str_replace('[%', '$displayrows[', $display); $display = addslashes(str_replace('%]', ']', $display)); $display = replaceTokens($display); $display = changeCase($display); eval("\$display = \"$display\";"); $display = stripslashes($display); $display = str_replace('[backslash]', '\\', $display); $display = replaceChar($display); print_r( $display ); } // output post content eval("\$postContent = \"$postContent\";"); print_r( replaceChar($postContent) ); ?> And here is part of the template (ppcindexcontent.php) the above code is reading. <div style=" float:right; width: 300px; height: 0px; margin-top:-20px ; margin-bottom:0px"> <p style=" font-size:16px; text-align: center; line-height:1; color:#0391D1;"> <?php error_reporting(E_ALL); ini_set('display_errors','On'); $mySQLServer = "xxxxxx"; $mySQLUser = "xxxxxxxx"; $mySQLPass = "xxxxxxxxx"; $mySQLDB = "xxxxxxxxxxx"; $SQLToday = date("m/d/y") . "<br />"; $SQLsevendays = mktime(0,0,0,date("n"),date("j")-7,date("Y")); $SQLsevenname = (date("l", $SQLsevendays)); $SQLsevennumber = (date("jS", $SQLsevendays)); $dbhandle = mssql_connect($mySQLServer, $mySQLUser, $mySQLPass) or die("Couldn't connect to SQL Server on $myServer"); $selected = mssql_select_db($mySQLDB, $dbhandle) or die("Couldn't open database $myDB"); $query = "WEB_ApproveHistory @State='CA', @Days=5, @Records=8"; $data = mssql_query($query); $result = array(); while ($row = mssql_fetch_object($data)) : $result[] = $row; $returnedresults = (97*($row->TotalApprovals)) ; endwhile; $englishreturnedresults = number_format($returnedresults); echo 'In just the last week since ' . $SQLsevenname . ' the ' . $SQLsevennumber . ' xx '; echo $englishreturnedresults; echo ' to People Just Like you In California. <br><br>Here are just a few people who' ; echo '<ul class="BulletCheck">'; mssql_next_result($data); while ($row = mssql_fetch_object($data)) : $result[] = $row; echo '<li>' . ' ' . $row->FirstName . ' From '. $row->City . ', ' . $row->State .' PreApproved On ' .$row->ApprovedDate . '</li>'; endwhile; mssql_close($dbhandle); ?> </div> 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 Code: [Select] $entrantQuery = "SELECT entrantID FROM entrants WHERE Game = $idT"; $entrantResult = mysql_query(entrantQuery); $entrantRow = mysql_fetch_row(entrantResult); I have these at the start of my php (after getting $idT), but I get the error Notice: Use of undefined constant entrantQuery - assumed 'entrantQuery' in C:\Entrants.php on line .. Notice: Use of undefined constant entrantResult - assumed 'entrantResult' in C:\www\Entrants.php on line.. Ive used this code lots of times before, what am I missing? They are variables that I am defining! hi, I have just used teh pagination from this site: http://papermashup.com/easy-php-pagination/ all is working ok apart from I get an error: Notice: Use of undefined constant num - assumed 'num' in D:\retroandvintage.co.uk\wwwroot\default.php on line 207 line 207: Code: [Select] $total_pages = $total_pages[num]; Please help? here is my site: http://www.retroandvintage.co.uk/default.php?page=5 Howdy Fairly new to the whole php scene made some php code which works, but i get the error Notice: Use of undefined constant Yes - assumed 'Yes' in C:\Program Files\EasyPHP-5.3.3\www\htdocs\top.php on line 26, line 26 is the first line code, kind of lost and would appreciate an explanation on how to fix this if possible thanks! Code: [Select] <?php if ($players['Banned'] == Yes){ echo $players['name'] ?> (BANNED) <?php } else {?> <a href="profile.php?id=<?php echo $players['id'] ?>"><?php echo $players['name'] ?> Hi, I have this code to assign a CSS style to a button dependingon which page we a Code: [Select] <td width="13%" valign="middle"><?php echo '<a href="PC_clientes_display.php"'; if(strstr($checkit,"PC_clientes_display.php")) echo ' class="clicked"'; else echo ' class="menulinks"'; echo '>CNT_TXT_ADMIN_CLIENTES</a>'; ?></td> Mi problem is that the constant CNT_TXT_ADMIN_CLIENTES is not displaying. I know it must be a syntax error but I can' seem to figure it out. Thanks!! I was wondering if there is a way to get a constant by using a variable connected to it, eg: define( 'CONSTANT_LOL', 'haha' ); $var = 'LOL'; echo CONSTANT_$var; Any help is appreciated, Chris How come I cannot do this? define('IMG_EXT', array("jpg", "jpeg", "png", "gif", "bmp", "tif"), true);
im getting these errors Notice: Use of undefined constant QUERY_STRING - assumed 'QUERY_STRING' in C:\xampps\htdocs\skyline\admin\other.php on line 36 and
<?php
$sql = "SELECT * FROM other "; Hi all, In my server at present php4 is running. upto now it is working fine.Suddenly it is showing lot of errors like Use of undefined constant or Undefined variable:. While trying in Google and all i came to know that the variable should be initialized and bounded by quotes.I checked in 1 file and it worked fine. But my coding is 99% completed and to change in every file is not an easy thing.Can anybody help regarding this Please? Here i'm having 1 more problem also which suffering me for a long time. I'm having one login form in this.That user session is working properly in Chrome but not in Mozilla.Even in Chrome once i try to logoff and relogin again it is behaving like in Mozilla. anybody please help me regarding these 2 issues.Thanks in advance. this code doesn't work, why? define("DIR", "../../"); final class MyClass { private static $PATH = DIR . '../directory/'; } How do you establish a tax rate in a MySQL database to use in a form calculation, then be able to change the value to a new constant value from the form? Hi,
I would like to generate a constant value that change from a website to website but have an identical value for a single website. For example
$_SERVER['SERVER_ADDR']doesn't change for a single website, but easy to guess. an other idea is realpath(dirname(__FILE__))but this can change if the web application execute scripts located in sub directories of the main script that use this variable. So what other possibilities to get a constant value that doesn't change ? Thank you. cant understand this error as i seemed to have it defined in my config file...... helpppp Notice: Use of undefined constant TBL_MEMBERS - assumed 'TBL_MEMBERS' in /export/SOI-50/students/m2009/abhr428/web/WebIbs/Member.class.php on line 32 Query failed: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'abhr428.TBL_MEMBERS' doesn't exist Code: [Select] <?php define('DB_DSN','mysql:host=vega.soi.city.ac.uk;dbname=abhr428' ); define( "DB_USERNAME", "abhr428" ); define( "DB_PASSWORD", "" ); define( "PAGE_SIZE", 5 ); define( "TBL_MEMBERS", "members" ); define( "TBL_ACCESS_LOG", "accessLog" ); ?> members.class.php <?php require_once "DataObject.class.php"; class Member extends DataObject { protected $data = array( "id" => "", "username" => "", "password" => "", "firstName" => "", "lastName" => "", "joinDate" => "", "gender" => "", "favoriteGenre" => "", "emailAddress" => "", "otherInterests" => "" ); private $_genres = array( "crime" => "Crime", "horror" => "Horror", "thriller" => "Thriller", "romance" => "Romance", "sciFi" => "Sci-Fi", "adventure" => "Adventure", "nonFiction" => "Non-Fiction" ); public static function getMembers( $startRow, $numRows, $order ) { $conn = parent::connect(); $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM " . TBL_MEMBERS . " ORDER BY $order LIMIT :startRow, :numRows"; try { $st = $conn->prepare( $sql ); $st->bindValue( ":startRow", $startRow, PDO::PARAM_INT ); $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT ); $st->execute(); $members = array(); foreach ( $st->fetchAll() as $row ) { $members[] = new Member( $row ); } $st = $conn->query( "SELECT found_rows() AS totalRows" ); $row = $st->fetch(); parent::disconnect( $conn ); return array( $members, $row["totalRows"] ); } catch ( PDOException $e ) { parent::disconnect( $conn ); die( "Query failed: " . $e->getMessage() ); } } public static function getMember( $id ) { $conn = parent::connect(); $sql = "SELECT * FROM " . TBL_MEMBERS . " WHERE id = :id"; try { $st = $conn->prepare( $sql ); $st->bindValue( ":id", $id, PDO::PARAM_INT ); $st->execute(); $row = $st->fetch(); parent::disconnect( $conn ); if ( $row ) return new Member( $row ); } catch ( PDOException $e ) { parent::disconnect( $conn ); die( "Query failed: " . $e->getMessage() ); } } public function getGenderString() { return ( $this->data["gender"] == "f" ) ? "Female" : "Male"; } public function getFavoriteGenreString() { return ( $this->_genres[$this->data["favoriteGenre"]] ); } } ?> I'm implementing google's reCAPTCHA V2. It works almost perfectly except for the following error located in the recaptchalib.php:
Notice: Use of undefined constant success - assumed 'success' in (script location)
https://github.com/g...ecaptchalib.php
Anyone got an idea how to fix this?
Edited by tork, 28 November 2014 - 04:24 PM. I've followed every piece of advice (quotes, no quotes, $...) and nothing works. Here is the snippet of code that's generating the error. This woks fine in PHP 5, but I have to upgrade to 7. Warning if for line 71, which corresponds to where query3 starts.
if($numRows == 0) { Earlier in code, I define this: $numRows = mysql_num_rows($r); Thanks in advance for any help you can lend. Edited February 7 by Poet |