PHP - Undefined Constant.. And Undefined Variable :?
I am pretty sure I defined these, by making it something like
$blah="blah" and `blah` = ' {$blah}' So why am I getting these errors = Notice: Use of undefined constant petid - assumed 'petid' in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 38 Notice: Use of undefined constant adopter - assumed 'adopter' in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 41 Notice: Undefined variable: fulldate in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 44 Fatal error: Call to undefined function showpet_forum() in /home/vhosts/foggyjungle.6te.net/viewpet_forum.php on line 45 $time = mysql_query("SELECT * FROM `pets_adopted`"); $date = mysql_fetch_array($time); $fulldate = "$date[fulldate]"; $halfdate = "$date[halfdate]"; function check(){ $pid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT * FROM `pets_adopted` WHERE `id` = '{$pid}'"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $results = mysql_query("SELECT * FROM `pets_list` WHERE `id` = '{$row[petid]}'"); $pet = mysql_fetch_array($results); $results2 = mysql_query("SELECT * FROM `users` WHERE `id` = '{$row[adopter]}'"); $usercc = mysql_fetch_array($results2); There's the snippet. Thank you for any help. I am just really lost. Similar TutorialsI have just re-installed Xampp and suddenly my sites are now displaying lots of: Notice: Use of undefined constant name - assumed 'name' in ... Notice: Use of undefined constant price - assumed 'price' in ... this is an example of the line its refering too: $defineProducts[1001] = array(name=>'This is a product', price=>123); Hello, I have just upgraded my wampserver and with it MySQL, PHP and PhpMyAdmin versions. And my scripts, which ran normally before, not burst hundreds of undefined variable and undefined index notices. I realize it's "notices", not "errors" but this is quite irritating. I believe it might be due to some upgrade in PHP scripting rules or something but I don't know what. I hope you can help me. The first type of notice is "undefined variable". This function will return the notice if I remove the bold red line, where I define the variable as empty before I use it in the loop. I didn't need to do this before. function statistics($array) { [color=red][b]$list = '';[/b][/color] if(is_array($array)) { foreach($array as $name => $value) { // Rip out the name of the client. $list .= "<li>".$name." - "; // set an integer so we know how many tier2 values we have read. $x = 0; foreach($value as $difference => $sum_total) { // if this is the more than the first tier2 values, use a '+' between the units. $list .= (++$x > 1) ? " + ".$sum_total." ".$difference : $sum_total." ".$difference; } // close the line out. $list .= "</li>"; } } return $list; } To avoid the 10+ like notices on the page I declare them empty before the variable's first occurrence. But this sounds stupid to me. Wasn't this one of PHP's benefits, not to have to declare the variable before using it? I also get about 30+ undefined index notices, e.g. Quote Notice: Undefined index: COMPANY XXX in F:\wamp\www\Project Management\main.php on line 37 Notice: Undefined index: USD in F:\wamp\www\Project Management\main.php on line 37 Notice: Undefined index: USD in F:\wamp\www\Project Management\main.php on line 41 Here are those lines: $income_total = calculate("income"); foreach($income_total as $row) { $clientID = $row['clientID']; $clientname = $row['clientname']; //$client = "<a href=\"index.php?page=Client&do=view&clientID=$clientID\">".$clientname."</a>"; $client = "<a href=\"index.php?page=Project&do=view&sortby=$clientID\">".$clientname."</a>"; $currency = $row['currency']; $client_sum = $row['client_sum']; $year_sum = ''; $year_sum += $client_sum; $income = ''; $income[$client][$currency] += $client_sum; $income_list = statistics($income); $income_all = ''; $income_all[$currency] += $client_sum; } Line 37 is: Quote $income[$client][$currency] = It's the values assigned to $client and to $currency that seem to cause the notice. How do I deal with this? I don't just want to turn error/notice display off, I want to resolve this issue. 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}; ?> 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! 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> 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'] ?>
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. Hello!
First of all, i would like to thank everyone in this community as this is where i post most of the problems that i can no longer fix on my own. and everytime i do, i get all the help i need and with a 100% success rate.
Anyway, i am following a tutorial, however the tutorial is based on a MAC environment and i am working on windows. I think this is a problem with the DIRECTORY_SEPARATOR but i might be wrong.
I am getting this error message "Notice: Use of undefined constant LIB_PATH - assumed 'LIB_PATH' in C:\wamp\www\beyond_basics_photogallery\includes\database.php on line 2"
i will just post the code that is relevant to this error. here is the code for database.php: (config.php is in the same folder with database.php)
require_once(LIB_PATH.DS."config.php");and this is my initialize.php where i initialized my DIRECTORY_SEPARATOR. this is also located in the same folder with database.php <?php // Define the core paths // Define them as absolute paths to make sure that require_once works as expected defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR); defined('SITE_ROOT') ? null : define('SITE_ROOT', DS.'wamp'.DS.'www'.DS.'beyond_basics_photogallery'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes'); // load config file first require_once(LIB_PATH.DS.'config.php'); // load basic functions next so that everything after can use them require_once(LIB_PATH.DS.'functions.php'); // load core objects require_once(LIB_PATH.DS.'session.php'); require_once(LIB_PATH.DS.'database.php'); // load database-related classes require_once(LIB_PATH.DS.'user.php'); ?>and this is the path to my project folder: C:\wamp\www\beyond_basics_photogallery I have tried everything i could but i am completely lost as to what is causing this. could it be the SITE_ROOT statement? i appreciate any help. thanks! 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 Poetcant 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"]] ); } } ?> Hi All, I am using PHP 5.3 and storing php session data to the database using session.set_save_handler callbacks. I see that the write method, strangely treats the Class constant as undefined. All the other methods seem to work fine with the class constant. Any reason why this would happen? Please see code below. I get an error "Use of undefined constant db_table in Sessions.php in line". This seems to be happening only with the write api. Can someone please help? Thanks class Sessions { //var $life_time; var $id; var $data; const db_table = 'php_mysql_session'; function PHPSessions() { // Read the maxlifetime setting from PHP //$this->life_time = get_cfg_var("session.gc_maxlifetime"); $this->id = session_id(); $this->data = ''; // Register this object as the session handler session_set_save_handler( array( &$this, "_open" ), array( &$this, "_close" ), array( &$this, "_read" ), array( &$this, "_write" ), array( &$this, "_destroy") , array( &$this, "_gc" ) ); } function _open () // open the session. { Zend_Log::log("opening connection"); global $_sess_db; Zend_Log::log("session db ".$_sess_db); if ($_sess_db = mysql_connect(DB_HOST_READ, DB_USER, DB_PASS)) { return mysql_select_db('TEST_SESSION', $_sess_db); } // If there is a failure return false return FALSE; } // open function _close () // close the db connection here { global $_sess_db; return mysql_close($_sess_db); } // close function _read ($id) // read any data for this session. { global $_sess_db; Zend_Log::log("Session db ".$_sess_db); //$id = mysql_real_escape_string(session_id()); Zend_Log::log("Session Id :" .$id); $sql = "SELECT * FROM ". self::db_table ." WHERE session_id = '$id'"; Zend_Log::log("SQL IS : ".$sql); $data = ''; $result = mysql_query($sql); $a = mysql_num_rows($result); Zend_Log::log("Record count ".$a); if($a > 0) { Zend_Log::log("Record Exists!"); $row = mysql_fetch_assoc($result); $data = $row['session_data']; Zend_Log::log("Fetching session Data ".$data); return $data; } else { Zend_Log::log("No Data ".$data); return ''; } } function _write ($id, $data) // write session data to the database. { global $_sess_db; $newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data); $sql = "REPLACE ". self::db_table ." (session_id,user_id,session_data,date_created) VALUES('$newid', '$userid', '$newdata', 'NOW()')"; $rs = mysql_query($sql); return TRUE; } // write function _destroy ($id) // destroy the specified session. { Zend_Log::log("Destroy method "); return TRUE; } // destroy function _gc ($max_lifetime) // perform garbage collection. { Zend_Log::log("GC Method"); return TRUE; } // gc function _destruct () // ensure session data is written out before classes are destroyed // (see http://bugs.php.net/bug.php?id=33772 for details) { @session_write_close(); } // __destruct // **************************************************************************** } // end class hi, I need help really badly for my PHP-Postcard Script. Basically it sends the card out but the URL does not work, I get the following error message: The URL is not valid and cannot be loaded It also states that Notice: Undefined index: www.voluntary.awardspace.co.uk in /home/www/voluntary.awardspace.co.uk/Postcard.php on line 25 Notice: Undefined index: Postcard.php in /home/www/voluntary.awardspace.co.uk/Postcard.php on line 25 See Code below: <?php session_start(); //check error log ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL); // CHANGE PARAMETERS HERE BEGIN $senderName = " Holidays From Home "; // Eg.: John's Postcards $senderEmail = "chris01@voluntary.awardspace.co.uk"; // Eg.: john@postcard.com // Change only if you have problems with urls $postcardURL = "http://".$_SERVER["www.voluntary.awardspace.co.uk"].$_SERVER["Postcard.php"]; // CHANGE PARAMETERS HERE END $result = 0; $msg = ""; $msg1 = ""; $pic = ""; function displayPhotos() { global $pic; $columns = 5; $act = 0; $act1 = 0; // Open the actual directory if($handle = opendir("thumbs")) { // Read all file from the actual directory while($file = readdir($handle)) { if(!is_dir($file)) { if(isset($pic[1])) { if($pic[1] == $act1){$sel = "checked";} else{$sel = "unchecked";} } if($act == 0){echo "<tr>";} echo "<td align='center'><img src='thumbs/$file' alt='postcard'/><br/><input type='radio' name='selimg' value='$file,$act1' $sel/></td>"; $act++; $act1++; if($act == $columns){$act = 0;echo "</tr>";} } } echo "</tr>"; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html> <head> <title>Micro Postcard</title> <link href= "style/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"> <div class="style1" id="caption"> <div align="left" class="style1"></div> </div> <?php //makes sure form is correctly filled in if(!empty($_POST["submit"])) { if(empty($_POST["selimg"])){$msg = "Please select an image from above!";$result = 3;} else{$pic = explode(",",$_POST["selimg"]);} if(empty($_POST["email"]) && empty($result)){$msg1 = "You must enter an email address!";$result = 3;} $secCode = empty($_POST["secCode"]) ? "" : strtolower($_POST["secCode"]); if($secCode == $_SESSION["securityCode"] && $result != 3) { $filename = date("YmdGis"); $f = fopen("messages/".$filename.".txt","w+"); fwrite($f,$pic[0]."\n"); fwrite($f,$_POST['email']."\n"); fwrite($f,stripslashes($_POST["message"])."\n"); fclose($f); // Compose the mail $from = "From: $senderName <$senderEmail>\r\n"; $replay = "Reply-To: $senderEmail\r\n"; $params = "MIME-Version: 1.0\r\n"; $params .= "Content-type: text/plain; charset=iso-8859-1\r\n"; $mailtext = "You have just received a Virtual Postcard!\r\n\r\n You can pick up your postcard at the following web address:\r\n $postcardURL?show=$filename\r\n\r\n We hope you enjoy your postcard, and if you do, please take a moment to send a few yourself!\r\n\r\n Regards,\r\n Holidays From Home\r\n $postcardURL"; // Send email @mail($_POST["email"],"You've received a postcard",$mailtext,$from.$replay.$params); echo "<center> Your postcard was sent successfully!<br /><br /> <img src='images/$pic[0]' alt='postcard' /><br /><br /><br />".stripslashes($_POST["message"]). "</center>"; $result = 1; } else{if($result != 3){$result = 2;}} } if(!empty($_GET["show"])) { $file = $_GET["show"]; $content = file("messages/$file.txt"); $pic = $content[0]; unset($content[0]); unset($content[1]); foreach($content as $value){$main .= $value;} echo "<center> Your postcard!<br /><br /> <img src='images/$pic' alt='postcard' /><br /><br /><br />$main </center>"; } if((empty($result) || $result == 2 || $result == 3) && empty($_GET["show"])) { echo "<form action='#' method='post'> <table align='center'>"; displayPhotos(); echo "</table> <div style='color:#f00;font-size:16px;'>$msg</div> <h2>Fill in the Form and then click on Send Card!!</h2> <table width='100%'> <tr><td>Send to (email address):</td><td><div style='color:#f00;font-size:16px;'>$msg1</div><input type='text' name='email' size='30' value='".$_POST["email"]."' /></td></tr> <tr><td>Message:</td><td><textarea name='message' rows='10' cols='40'>".stripslashes($_POST["message"])."</textarea></td></tr> <tr><td colspan='2'>".($result == 2 ? "<p style='color:#f00;font-size:16px;'>Sorry the security code is invalid! Please try it again!</span></p>" : " ")."</tr> <tr> <td>Security code: <input class='text' name='secCode' type='text' size='10' /> </td><td><img src='securityCode.php' alt='security code' border='1' /></td> </tr> <tr><td colspan='2'> </tr> <tr><td colspan='2' align='left'><input type='submit' value='Send card!' name='submit'/></td></tr> </table> </form>"; } ?> Absolutely any help would be much appreciated. I want ot know is there a way round this problem? Here is the http://voluntary.awardspace.co.uk/Postcard.php I am absolutely desperate to solve this burning issue Notice: Use of undefined constant DB_DSN - assumed 'DB_DSN' in /export/SOI-50/students/m2009/abhr428/web/WebIbs/DataObject.class.php on line 32 dataobject.class.php can understand this problem has it got anything to with the config.php file which contains is this the reason for the above error or is it something else in the dataobjects.php below config.php <?php define( "DB_DSN", mysql:dbname=abhr428 ); define( "DB_USERNAME","" ); define( "DB_PASSWORD", "040010722" ); define( "PAGE_SIZE", 5 ); define( "TBL_users", "users" ); define( "TBL_accesslog", "accesslog" ); ?> dataobject.class.php <?php require_once "config.php"; abstract class DataObject { protected $data = array(); public function __construct( $data ) { foreach ( $data as $key => $value ) { if ( array_key_exists( $key, $this->data )) $this->data[$key] = $value; } } public function getValue( $field ) { if ( array_key_exists( $field, $this->data )) { return $this->data[$field]; } else { die( "field not found" ); } } public function getValueEncoded( $field ) { return htmlspecialchars( $this->getValue( $field )); } protected function connect() { try { $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $Conn->setAttribute( PDO::ATTR_PERSISTENT, true ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch ( PDOException $e) { die( "connection failed: " . $e->getMessage() ); } return $conn; } protected function disconnect( $conn ) { $conn = ""; } } ?> When I run the MySQL queries in the code below in SQLyog, the $pokemon_pos in the "SELECT max(pokemon_pos)" part of the statement is always correct (i.e. alias "x" is correct). Yet when wrapped up in PHP, $newpos, which relies on "x" is always undefined. I'd greatly appreciate any help in troubleshooting this code - Code: [Select] $getdeclined="SELECT * FROM trade_offers WHERE pokemon_trade_id=$_GET[id]"; $declined=mysql_query($getdeclined); while ($row = mysql_fetch_array($declined)){ $getdecusername="SELECT MAX(pokemon_pos) FROM ( SELECT pokemon_pos FROM pokemon_trainer WHERE pokemon_trainer = '$row[pokemon_trainer]' UNION SELECT pokemon_pos FROM trade_offers WHERE pokemon_trainer = '$row[pokemon_trainer]' AND pokemon_trade_id = $_GET[id] ) AS x"; $decusername=mysql_query($getdecusername); while($row2 = mysql_fetch_array($decusername)){ $newpos = $row2['x'];} echo $newpos; $newpos +=1; } } I had some help righting this query and the extensive coding here and most of it I understand however when i run this it gives me an undefined variable charname error and I'm trying to understand why. Does the coding make sense to anyone? <?php $query = "SELECT ecm.name AS fighters, ecb.id AS showid, ecm.id AS matchid, ecb.bookingdate AS bookingdate, ecb.event_id AS event_id, els.name AS name, ecb.label AS label FROM `efed_content_appearances` AS eca INNER JOIN `efed_content_matchseg` AS ecm ON eca.content_id = ecm.id INNER JOIN `efed_content_booking` AS ecb ON ecm.booking_id = ecb.id INNER JOIN `efed_list_shownames` AS els ON ecb.event_id = els.id WHERE eca.bio_id = '$id' AND eca.type = 'match' ORDER BY ecb.bookingdate DESC, ecm.sortorder ASC"; $result = mysql_query($query); if(mysql_num_rows($result) == 0){ echo '<td colspan="3" class="noseg">This wrestler has never been in an event match.</td>' ; } else{ $count = 1; while($row = mysql_fetch_assoc($result)){ $fighter = explode(' vs. ', $row['fighters']); $opponents = ''; for($i = 0; $i < count($fighter); $i++){ if($fighter[$i] != $charname){ if($opponents != ''){ $opponents .= ', '; } $opponents .= $fighter[$i]; } } echo '<table cellspacing="0px" style="text-align: center;"><tr class="titlebar"><td>Date</td><td>Show</td><td>Opponent/s</td></tr>'; echo '<tr class="row' . $count . '"><td>' . convertdate($row['bookingdate']) . '</td><td><a href="content.php?p=results&show=' . $row['event_id'] . '&id=' . $row['showid'] . '#' . $row['matchid'] . '">' . $row['name'] . ' ' . $row['label'] . '</a></td><td>' . $opponents . '</td></tr>'; echo '</table>'; if($count == 1){ $count = 2; } else { $count = 1; } } } ?> Why does php show undefined variable? I researched and found out that if the variables aren't set then they will likely show undefined variable. However, I used the isset function to check if the variable is undefined and if it is then set it to $varaible ="" . That didn't work and then later i tried $variable = NULL. What should I do Can you please see the code and tell me what shall i do. Thanks a million
<?php require_once("includes/connection.php")?> <?php require_once("includes/function.php") ?> <?php require_once("includes/header.php") ?> <?php if(isset($_GET['subj'])){ $sel_subj = NULL; $sel_subj = $_GET['subj']; } elseif (isset($_GET['page'])){ $sel_page = NULL; $sel_page = $_GET['page'] ; } else { $sel_subj= NULL; $sel_page =NULL; } ?> <table id = "structure" > <tr> <td id = "navigation" > <ul class= "subjects" > <?php $subject_set = get_all_subjects(); while ($subject = mysql_fetch_array($subject_set)){ // <a href = "content.php?subj=1" > if ($sel_subj == $subject["id"]){ echo "<li class = \"selected\" "; }else{ echo "<li> "; } "<a href = \"content.php?subj=" . urlencode($subject["id"]) . "\">" . $subject["menu_name"]. "</a></li>" ; $page_set = get_pages_for_subjects( $subject["id"] ) ; echo " <ul class = \"pages\"> "; while ($page = mysql_fetch_array($page_set)){ echo "<li><a href = \"content.php?page=" . urlencode($page["id"]) . "\">" . $page["menu_name"] . "</a></li>" ; } echo "</ul>" ; } ?> </ul> </td> <td id= "page" > <h1> Main Area To Get Your Information </h1> <?php echo $sel_subj ; ?> <br/> <?php echo $sel_page ; ?> <br/> </td> </tr> </table> <?php include ("includes/footer.php") ?>The variable im refering to is $sel_subj and $sel_page at the top of the code. Here is an attachment of the error Attached Files Capture.PNG 275.47KB 0 downloads can anyone help with this function. i keep getting undefined variable: link error. function simple_query($fields, $table, $clause, $order) { if (empty($config)) { require("./config/config.php"); } if(!empty($clause)) { $clause = "WHERE $clause"; } if(!class_exists('db_mysqli')) { include('./includes/db_mysqli.php'); $link = new db_mysqli; $link->connect($config['database']); } if(!empty($order)) { $direction = $order[0]; switch($direction) { case "0": $direction = "ASC"; break; case "1": $direction = "DESC"; break; } $order = substr($order, 1, strlen($order)); $order = "ORDER BY $order $direction"; } $query = $link->query("SELECT $fields //THIS LINE THROWS THE ERROR FROM ".TBL_PREFIX."$table $clause $order")or die(mysqli_error($link)); return $query; } database class: class db_mysqli { public $link; function connect($settings) { require_once(dirname(dirname(__FILE__)).'/config/config.php'); $link = new mysqli($settings['hostname'], $settings['username'], $settings['password'], $settings['database']); $this->link = $link; } } thanks. |