PHP - Constant And Class Problem
this code doesn't work, why?
define("DIR", "../../"); final class MyClass { private static $PATH = DIR . '../directory/'; } Similar TutorialsHello!
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! Hi, 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{ Hey guys! I have spent the last 5 and a half hours banging my head up against the wall trying to fix this to no avail so I guess its time to ask the experts!!! I am having a problem with my membership class. Basically, it works perfectly if a user logs in using sessions and not cookies. But when remember is set to 1 (they ticked the remember me checkbox), the mysql query fails on this line when we run $member_class->member_class(); Code: [Select] $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); Everything matches up except for the $token value. Basicly I believe that a new token is updated in the mysql database, before the token value in the cookie is updated as when I print $token, it definitly matches up with the token value in the mysql database. But from reading through the code, it all looks perfectly fine to me which is why i am so confused. If i change $newtoken = $this->token(); // generate a new token to $newtoken = '1234'; the script also works perfectly fine without errors (though not very secure so would like the token to change values! Really appreciate any input! Cheers <?php // member class // handlers member logon class member_class { var $message = ''; var $query_error = 'ERROR: something went wrong when accessing the database. Please consult your webmaster'; function member_class() { //constructor if (!$_SESSION['member_id']) { //fills session with empty values $this->set_session_defaults();; } if ($_SESSION['logged_in']) { //already logged in $this->check_session(); } if ($_COOKIE['remember']) { $this->check_remembered($_COOKIE['remember']); } } function check_login($email,$password,$remember,$redirect) { $email = mysql_escape_string($email); $salt='s+(_v'; $password = mysql_escape_string(hash('sha512', $salt . $password)); $result=mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND password = '{$password}'"), MYSQL_ASSOC); if ($result) { $this->set_session($result,$remember,true); return true; } else { $this->failed = true; $this->logout(); //create error message telling user that either the email address does not exist, or they have entered the wrong password associated with the email address $result=mysql_fetch_array(mysql_query("SELECT email FROM members WHERE email = '{$email}'")); if($result) { $this->message .= 'Incorrect Password. Please try again'; } else { $this->message .= 'The email address '.$email.' does not exist. Please try again or <a href="/register.php" class=" cboxElement">create a new account</a>.'; } return false; } } function logout() { // blowup cookie setcookie('remember',time()-3600); $this->set_session_defaults(); } function set_session($result,$remember,$init = true) { $member_id=$result['member_id']; if ($init) { $session = mysql_escape_string(session_id()); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); $newtoken = $this->token(); // generate a new token // generate a random token $update = mysql_query("UPDATE members SET session='{$session}', token='{$newtoken}', ip_address='{$ip_address}' WHERE member_id='{$member_id}'") or DIE ($this->query_error); } $_SESSION['member_id'] = $result['member_id']; $_SESSION['email'] = htmlspecialchars($result['email']); $_SESSION['fullname'] = $result['fullname']; $_SESSION['token'] = $newtoken; $_SESSION['logged_in'] = true; if ($remember) { $this->update_cookie($newtoken); } } function update_cookie($token) { $cookie = serialize(array($_SESSION['email'],$token)); //print $token; setcookie('remember',$cookie, time()+12099600); } function check_remembered($cookie) { $serializedArray=$cookie; $serializedArray = stripslashes($serializedArray); list($email,$token) = unserialize($serializedArray); if(empty($email) or empty($token)) { return; } else { $email = mysql_escape_string($email); $token = mysql_escape_string($token); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //changed from = '{ip_address} to like '{ipaddress}% so we are not strict in ip address we only limit to first 3 charactors of ip $ip_address = substr($ip_address, 0, 3); $query = "SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"; print $query; $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); if (!$result) { // $this->set_session($result,false,false); }else{ $this->set_session($result,true,true); } } } function token() { // generate a random token for($i=1;$i<33;$i++) { $seed .= chr(rand(0,255)); } return md5($seed); } function check_session() { $email = mysql_escape_string($_SESSION['email']); $token = mysql_escape_string($_SESSION['token']); $session = mysql_escape_string(session_id()); //if ip address changes it will fail POSSIBLY DO NOT NEED THIS! $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //check only the first 4 charactors of ip address incase user changes ip in corporate workplace etc ALSO CHANGED = TO LIKE IN MYSQL QUERY AND ADDEED % TO THE END AS WILDCARD $ip_address = substr($ip_address, 0, 3); $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email='{$email}' AND token='{$token}' AND session='{$session}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC or DIE ($this->query_error)); if ($result != false){ }else{ $this->logout(); } } }?> Hi, this php code not working for some reason Code: [Select] class db { public function connect() { $yhteys = new PDO("mysql:host=*****;dbname=*****", "*******", "******"); } public function get($query, $parameters){ $prepare = $yhteys->prepare($query); $prepare->execute($parameters); $result = $prepare->fetch(); $count = $prepare->rowCount(); return array($result, $count); } } Code: [Select] $db = new db(); $content = $db->get("SELECT * FROM tuotteet WHERE id = ?", array("1")); print $content; It gives error:Parse error: syntax error, unexpected T_OBJECT_OPERATOR Thank you for help! class Z { function foo() { // do somethig } } class X { $x function __contruct() { $this->x = new z(); } function var() { $this->x->foo(); // Fatal error: Using $this when not in object contex } } // Class declaration here class Y { function __contruct() { $z = new z(); $x = new x(); } } 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 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 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'] ?> 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 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 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 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}; ?> 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. 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 got some help from this forum previously and am having some more issues. I created a database class that works and returns a PDO object. I am having trouble figuring out how to use the object in another class I want to use to access some CRUD functions. I get to the point where I start using the pdo object I create in the database class and my code fails. I am obviously calling the pdo object property incorrectly. I guess I don't understand the proper syntax. I've included the code for the database class and the CRUD class. The problem starts at the point where I try to run a prepared statement. I have include a comment "Problem stars here" to indicate that point. There is a lot of debug stuff still in the code. Thanks, --Kenoli <?php class Db { public $pdo = ''; public $message = 'A message from db!<br><br>'; function __construct() { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "tio-local"; $db_options = array( PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); try { $this->pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, $db_options); // set the PDO error mode to exception $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // End Try catch(PDOException $e) { echo "Error: " . $e->getMessage(); } } // End __construct } // End class definition DB.php $db = new Db; $pdo = $db->pdo; print_r ($pdo); ?> <?php // Db_functions.php include_once ('Db.php'); // $db instantiated in class file $pdo = $db->pdo; class Db_functions { public $pdo = ''; function __construct($pdo) { $this->pdo = $pdo; } // Close __construct public function insert($table_name, $white_list, $insert_array) { if ($white_list == '' && $table_name == 'Sites') { $white_list = array('gone'=>'','site_name' =>'', 'site_address' =>'', 'grommets' =>'', 'tape' =>'', 'site_image' =>'', 'description' =>'', 'surface' =>'', 'tio_contact' =>'', 'site_contact' =>'','owner' =>'', 'lessee' =>'', 'contact_phone' =>'', 'contact_email' =>'', 'contact_date' =>'', 'comments' =>''); } elseif ($white_list == '' && $table_name == 'Persons') { $white_list = array('gone'=>'', 'fname'=>'', 'lname'=>'', 'tio'=>'', 'volunteer'=>'', 'general'=>'', 'artist_pic'=>'', 'email'=>'', 'website'=>'', 'telephone'=>'', 'address'=>'', 'city'=>'', 'state'=>'', 'zip'=>'', 'statement'=>''); } echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); echo '<p>The following is the $white_list:<br>'; echo '<pre>'; print_r ($white_list); echo '</pre>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Test and remove any unpermitted columns **/ $insert_array = array_intersect_key($insert_array, $white_list); echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Generate variables to create prepared statements **/ foreach($insert_array as $key => $value) { $col .= $key . ', '; $val .= ':' .$key . ', '; } echo '$col = ' . $col . '<p>'; echo '$val = ' . $val . '<p>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Remove ', ' at end of arrays and create prepared statement */ $col = substr_replace($col ,"",-2); $val = substr_replace($val ,"",-2); $sql = "INSERT INTO Sites ($col) VALUES ($val)"; echo "<p>SQL = $sql<br><br>"; /** Debug **/ echo '<h3>More</h3<br>'; /** Register prepared statement */ /****** PROBLEM STARTS HERE *****/ $stmt = $this->pdo->prepare($sql); echo '<h3>More2</h3>'; /** Create [:field, $value] pairs. */ foreach($insert_array as $key => $value) { $param = ':' . $key; $stmt->bindParam($param, $$value); //} /** Create [field => value] array */ foreach($insert_array as $key => $value) { $insert[$key] = $value; } /** Execute statement using $insert array. **/ $stmt->execute($insert); } // End insert function } // Close class definition $db_functions = new Db_functions($pdo); $insert_array = array('fname' => 'John', 'lname' => 'Hancock'); $db_functions->insert('Persons', '', $insert_array); echo '<pre>'; print_r ($db_functions); echo '</pre>'; ?> Edited February 6 by kenoli I have the code as given below: <?php class ABC { function printValue() { print("This value shall be printed" . $this->x); } } class BCD extends ABC { private $x=10; } $bcd=new BCD; $bcd->printValue(); ?> But when I try to access printValue function from the paren class it gives me error... Fatal error: Cannot access private property BCD::$x in /var/www/html/trainingweb/modules/test/TestAtitProblem.php on line 5 As the public method of ABC would be extended to BCD, it shall have access to its own member. please help... Hey guys im just starting to use Prepared Statements in php and i am trying to build a search but i have come across a problem. Hope someone can help or point me to more information on how to resolves this. Ok here is the code below:: public function search($string) { if(strlen($string) > 40) { return "Woow too many words, please shorten your search."; } if(empty($string)) { return "I'm a search, you type things in and I find. Please enter something and try again!"; } if(strlen($string) <= 3) { return "Come on dude, you expect me to find summin with that? Type some more tags in!"; } $x=0; // Teh string could be multiple searches so explode:: $string = explode(" ", $string); foreach($string as $search) { $x++; if($x == 1) { @$sql .= "(blog_tags LIKE '%$search%')"; } else { @$sql .= " OR (blog_tags LIKE '%$search%')"; } } $sql = "SELECT blog_tags FROM subarc_blog WHERE $sql LIMIT 40"; // TODO:: Count how many search results found:: $stmt = $this->conn->prepare($sql); $stmt->execute(); $stmt->bind_result($search); Ok by using the bind_result() i need to know how many result are being returned to add them to a variable is this correct ? if so how can i tell how many results have been returned ? hope this makes sense Hi im having trouble getting the below code to listen to my css margin settings. Just to clear up the server side of things, can anybody tell me wether or not im using the correct syntax in the code below? Code: [Select] else { echo("<p class=\"passed\">Thankyou for submiting your details, you will be added to our directory shortly</p>"); }} |