PHP - Error: Using $this When Not In Object Context
I'm trying to build a Wordpress plugin where all the archives are nicely listed in a tabular form. I'm reading the book Wordpress Plugin Development - A Beginner's Guide
And I'm having an error when trying to call the function to display the archives on a separate page. Here's the function: function display() { global $wpdb; // these variables store the current year, month and date // processed $curyear=''; $curmonth=''; $curday=''; // the beginning of our output $result=' <div class="snazzy"> <table cellspacing="15" cellpadding="0" border="0"> <tbody> <tr>'; // query to get all published posts $query= "SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_password='' ORDER BY post_date_gmt DESC "; $posts = $wpdb->get_results($query); foreach ($posts as $post) { // retrieve post information we need $title = $post->post_title; $excerpt= $this->get_excerpt($post->post_content); $url=get_permalink($post->ID); $date = strtotime($post->post_date); // format the date $day = date('d', $date); $month = date('M', $date); $year = date('Y', $date); // look for image in the post content $imageurl=""; preg_match('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*) /i' , $post->post_content, $matches); $imageurl=$matches[1]; // get comments for this post $comcount = $wpdb->get_var(" SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_post_ID=$post->ID AND NOT (comment_type = 'pingback' OR comment_type = 'trackback')"); // additional formatiing if ($year!=$curyear) { // close the previous day/month if ($curday) $result.="</div></div></td>"; $curday=''; $curmonth=''; // year start in a new column (<td>) $result.= '<td valign="top"><div class="sz_date_yr">' .$year.'</div><div class="sz_cont">'; $result.= '</div></td>'; $curyear=$year; } if ($month!=$curmonth) { // close the previous day/month if ($curday) $result.="</div></div></td>"; $curday=''; // month starts in a new column (<td>) $result.= '<td valign="top"><div class="sz_date_mon">' .$month.'</div><div class="sz_month">'; $curmonth=$month; } if ($day!=$curday) { // close previous day if ($curday) $result.="</div>"; $result.= '<div class="sz_date_day">'.$day.' </div><div class="sz_day">'; $curday=$day; } // retrieve the archive entry representation ob_start(); include('snazzy-layout-1.php'); $output = ob_get_contents(); ob_end_clean(); $result.=$output; } // close the previous day/month if ($curday) $result.="</div></div></td>"; // close the main page elements $result.="</tr></tbody></table></div>"; // return the result return $result; } This is the part to which the error message is referring to: // retrieve post information we need $title = $post->post_title; $excerpt= $this->get_excerpt($post->post_content); $url=get_permalink($post->ID); $date = strtotime($post->post_date); // format the date $day = date('d', $date); $month = date('M', $date); $year = date('Y', $date); The error message says that I'm using $this when not in "object context". The part where $this is used is needed to display an excerpt of the post content. This is the same way how it's shown in the book, for some reason it doesn't work for me. What would be an alternative way that I could do to make it work, any ideas? Similar TutorialsI get the error code "Fatal error: Using $this when not in object context in /home/feenetwo/public_html/language/english/mails/sale_third_party_notification.php on line 7" when I complete the form from the link in the screenshot atached... the site is feenetwork.com and im getting really fustrated with it.... Can anyone help? First i will show the code that activates the error: Code: [Select] if($current_host != null) { print_r2("1"); print_r2($current_host); print_r2($current_foundResult); print_r2("2"); $current_host::addFoundResult($current_foundResult); } this is the output: Quote 1 Host Object ( [hostname] => www.google.nl [foundResults] => Array ( ) ) FoundResult Object ( [url] => [title] => [visits] => ) 2 Fatal error: Using $this when not in object context in ~~~~~~~~~~~~~ on line 385 the error comes from this line: $this->foundResults[] = $foundResult; Code: [Select] class Host { public $hostname; public $foundResults; public function __construct($hostname) { $this->hostname = $hostname; $this->foundResults = array(); } public function addFoundResult($foundResult) { $this->foundResults[] = $foundResult; } } what i don't get about it is that both the Host Object and the FoundResult Object exist... Hello. I am now dumbfounded (once again). I am using $this inside a class. I honestly have no idea what is going on. If anyone could give me a pointer that would be brilliant. Code: [Select] /* * List of functions in this class in order (construct and destruct are the only functions not in alphabetical order) * Construct * BooleanValue * BuildColumns * Connect * Clean * Delete * Disconnect * EndTransaction * Error * Insert * IsConnected * Kill * LastInsertID * Log * Query * RollbackTransaction * RowCount * Select * StartTransaction * Update * Where * Destruct */ class MySQL extends MySQLi { private $host = HOST; private $user = USER; private $pass = PASS; private $data = DATA; private $port = PORT; private $charset = CHARSET; const quote = "'"; // what quote to use /* Internal vars */ private $lastID = ""; private $lastResult = ""; private $queries = ""; private $link = 0; private $timeStart = 0; private $timeEnd = 0; private $timeTotal = 0; private $errorString = ""; private $errorNo = 0; private $in_transaction = false; private $queryQueue = ""; /* * Construct * Starts the connection unless autoconnect = false */ public function __construct($autoconnect = true) { $autoconnect === true ? $this->Connect() : false; } /* * End construct ***************************************************************************************************/ /* * BooleanValue * Determins whether the input is a boolean value, or can be converted into a boolean value */ static function BooleanValue($value) { $value = self::Clean($value); if(gettype($value) == "boolean") { if($value == true) { return true; } else { return false; } } elseif(is_numeric($value)) { if($value > 0) { return true; } else { return false; } } else { $str = strtoupper(mysqli_real_escape_string($this->link, trim($value))); if($str == "ON" || $str == "SELECTED" || $str == "CHECKED" || $str == "YES" || $str == "Y" || $str == "TRUE" || $str == "T") { return true; } else { return false; } } } /* * End BooleanValue ***************************************************************************************************/ /* * BuildColumns * Builds columns for use with SQL statements */ static function BuildColumns($columns, $addQuotes = true, $showAlias = true) { if($addQuotes) { $quote = self::quote; } else { $quote = ""; } switch(gettype($columns)) { case "array": $sql = ""; $i = 0; foreach($columns as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if($i == 0) { $sql = $quote.$value.$quote; $i = 1; } else { $sql .= ", ".$quote.$value.$quote; } if($showAlias && is_string($key) && (!empty($key))) { $sql .= " AS ".$quote.$key.$quote."'"; } } break; case "string": $columns = self::Clean($columns); return $quote.$columns.$string; break; default; return false; break; } return $sql; } /* * End BuildColumns ***************************************************************************************************/ /* * Connect * Connects to the database */ public function Connect() { $this->link = @mysqli_connect($this->host, $this->user, $this->pass, $this->data, $this->port); $this->IsConnected(); } /* * End Connect ***************************************************************************************************/ /* * Clean * Cleans input */ static function Clean($value) { $this->IsConnected(); $value = ltrim($value); $value = rtrim($value); $value = mysqli_real_escape_string($this->link, $value); return $value; } /* * End Clean ***************************************************************************************************/ /* * Delete * Deletes a record from the database */ public function Delete($table, $whereArray) { $sql = "DELETE FROM ".$table; $sql .= self::Where($whereArray); } /* * End Delete ***************************************************************************************************/ /* * Disconnect * Disconnects from the database */ public function Disconnect() { if($this->IsConnected()) { mysqli_close($this->link); } } /* * End disconnect ***************************************************************************************************/ /* * EndTransaction * Ends the transaction, saving all data to the database */ public function EndTransaction() { $this->IsConnected(); if($this->in_transaction) { if(!mysqli_query($this->link, "COMMIT")) { $this->RollbackTransaction(); } else { $this->in_transaction = false; return true; } } else { $this->Error("Not in a transaction", -1); return false; } } /* * End EndTransaction ***************************************************************************************************/ /* * Error * Handles Errors */ public function Error($errstr = "", $errno = 0) { try { if(strlen($errstr) > 0) { $this->errorString = $errstr; } else { $this->errorString = @mysqli_error($this->link); if(!strlen($this->errorString) > 0) { $this->errorString = "Unknown error"; } } if($errno <> 0) { $this->errorNo = $errno; } else { $this->errorNo = @mysqli_errno($this->link); } } catch(Exception $e) { $this->errorString = $e->getMessage(); $this->errorNo = -999; } $this->Kill(); } /* * End Error ***************************************************************************************************/ /* * Insert * Inserts a record into the database */ public function Insert($table, $valuesArray) { $columns = self::BuildColumns(array_keys($valuesArray), false); $values = self::BuildColumns($valuesArray, true, false); $sql = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")"; $this->queryQueue .= $sql; } /* * End Insert ***************************************************************************************************/ /* * IsConnected * Checks if there is a connection */ public function IsConnected() { if(@mysqli_ping($this->link)) { return true; } else { $this->Error(); return false; $this->RollbackTransaction(); $this->Kill("No connection present"); } } /* * End IsConnected ***************************************************************************************************/ /* * Kill * Rollsback anychanges and kills the script */ public function Kill() { $this->RollbackTransaction(); if(!$this->errorString) { $this->errorString = "Unknown"; } if(!$this->errorNo) { $this->errorNo = -999; } die("<br /><br /><strong>An error has occured.<br />".$this->errorString."<br />".$this->errorNo); } /* * End Kill ***************************************************************************************************/ /* * LastInsertID * Returns the last inserted ID */ public function LastInsertID() { return $this->lastID; } /* * End LastInsertID ***************************************************************************************************/ /* * Log * Logs all MySQL queries */ static function Log($page, $utime, $wtime, $mysql_time, $sphinx_time, $mysql_count_queries, $mysql_queries) { /*$table = "mysql-".date("Ymd"); $sql = "INSERT DELAYED INTO ".$table." (ip, page, utime, wtime, mysql_time, sphinx_time, mysql_count_queries, mysql_queries, user_agent) VALUES ("self::quote.$_SERVER['REMOTE_ADDR'].self::quote.", ".self::quote.$page.self::quote.", */ } /* * End Log ***************************************************************************************************/ /* * Query * Exectues all queries */ public function Query($sql) { $this->IsConnected(); $this->timeStart = microtime(true); $this->queries = $sql; $this->StartTransaction(); $this->lastResult = @mysqli_query($this->link, $sql); if(!$this->lastResult) { $this->RollbackTransaction(); $this->Error(); } $this->EndTransaction(); if(strpos(strtolower($sql), "insert") === 0) { $this->lastID = mysqli_insert_id($this->link); if($this->lastID === false) { $this->Error(); } else { return $this->lastResult; //$this->queryQueue = ""; } } elseif(strpos(strtolower($sql), "select") === 0) { $this->LastID = 0; } $this->timeEnd = microtime(true); $this->timeTotal = ($this->timeEnd - $this->timeStart); $removeE = explode('E', $this->timeTotal); $this->timeTotal = $removeE[0]; echo $this->queryQueue; } /* * End Query ***************************************************************************************************/ /* * RollbackTransaction * Un-does the changes made */ private function RollbackTransaction() { $this->IsConnected(); if(!mysqli_query($this->link, "ROLLBACK")) { $this->Error("Rollback failed. Manual cleanup required"); return false; } else { $this->in_transaction = false; return true; } } /* * End RollbackTransaction ***************************************************************************************************/ /* * RowCount * Returns the amount of rows effected from the last query */ public function RowCount() { return mysqli_num_rows($this->lastResult); } /* * End RowCount ***************************************************************************************************/ /* * Select * Selects rows * USAGE: * $result = $sql->Select("users", array("username" => "james")); * while($row = mysqli_fetch_array($result)) { * echo $row['password']; * } */ public function Select($table, $whereArray = null, $columns = null, $sortColumns = null, $sortAscending = true, $limit = null) { if(!is_null($columns)) { $sql = self::BuildColumns($columns); } else { $sql = "*"; } $sql = "SELECT ".$sql." FROM ".$table; if(is_array($whereArray)) { $sql .= self::Where($whereArray); } if(!is_null($sortColumns)) { $sql .= " ORDER BY ".self::BuildColumns($sortColumns, true, false). " ".($sortAscending ? "ASC" : "DESC"); } if(!is_null($limit)) { $sql .= " LIMIT ".$limit; } self::Query($sql); $return = ""; return $this->lastResult; } /* * End Select ***************************************************************************************************/ /* * StartTransaction * Starts the transaction */ private function StartTransaction() { if(!$this->IsConnected()) { die(); } if(!$this->in_transaction) { if(!mysqli_query($this->link, "START TRANSACTION")) { $this->Error(); return false; } else { $this->in_transaction = true; return true; } } else { $this->Error("Already in a transaction"); } } /* * End StartTransaction ***************************************************************************************************/ /* * Update * Updates the rows */ public function Update($table, $valuesArray, $whereArray = null) { $sql = ""; $i = 0; foreach($valuesArray as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if($i == 0) { $sql = $key." = ".self::quote.$value.self::quote; $i = 1; } else { $sql .= ", ".$key." = ".self::quote.$value.self::quote; } } $sql = "UPDATE ".$table." SET ".$sql; if(is_array($whereArray)) { $sql .= self::Where($whereArray); } self::Query($sql); return $this->lastResult; } /* * End Update ***************************************************************************************************/ /* * Where * Select rows where X */ public function Where($whereArray) { $where = ""; foreach($whereArray as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if(strlen($where == 0)) { if(is_string($key)) { $where = " WHERE ".$key." = ".self::quote.$value.self::quote; } else { $where = " WHERE ".self::quote.$value.self::quote; } } else { if(is_string($key)) { $where .= " AND ".$key." = ".self::quote.$value.self::quote; } else { $where .= " AND ".self::quote.$value.self::quote; } } } return $where; } /* * End where ***************************************************************************************************/ /* * Destruct * Closes the connection and cleans up */ public function __destruct() { if($this->queryQueue) { $this->Query($this->queryQueue); } $this->Disconnect(); } /* * End destruct ***************************************************************************************************/ } The code I am using to get the error is this: Code: [Select] $sql = new Mysql; $sql->Insert("users", array("username" => "James")); $sql->Insert("users", array("username" => "fds")); $sql->Insert("users", array("username" => "le")); Thanks. EDIT: Added code to call the error. Hello , I have a made a PHP website where users signup and send their Date of Birth and gets an OTP on their email after signup. The OTP is recieved but when we enter the OTP this problem occurs QuoteError! Something went wrong and I am facing this error in the error log QuotePHP Fatal error: Uncaught Error: Object of class DateTime could not be converted to string This is my config.php code <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Confirmation Page - Kanha Stories</title> <style> body { background-color: #330000; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 800 400'%3E%3Cdefs%3E%3CradialGradient id='a' cx='396' cy='281' r='514' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23D18'/%3E%3Cstop offset='1' stop-color='%23330000'/%3E%3C/radialGradient%3E%3ClinearGradient id='b' gradientUnits='userSpaceOnUse' x1='400' y1='148' x2='400' y2='333'%3E%3Cstop offset='0' stop-color='%23FA3' stop-opacity='0'/%3E%3Cstop offset='1' stop-color='%23FA3' stop-opacity='0.5'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23a)' width='800' height='400'/%3E%3Cg fill-opacity='0.4'%3E%3Ccircle fill='url(%23b)' cx='267.5' cy='61' r='300'/%3E%3Ccircle fill='url(%23b)' cx='532.5' cy='61' r='300'/%3E%3Ccircle fill='url(%23b)' cx='400' cy='30' r='300'/%3E%3C/g%3E%3C/svg%3E"); background-attachment: fixed; background-size: cover; padding: 20px; width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; color:#ffffff; overflow-x: hidden; } .cont { padding: 20px 40px; position: relative; border-right: 4px solid rgb(184, 182, 182); border-bottom: 4px solid rgb(184, 182, 182); border-radius: 15px; display: flex; flex-direction: column; align-items: center; } #left{ float: left; } #right{ float: right; } input{ margin: 10px 0px; } s{ padding: 5px; } .error{ padding: 5px; color: #ffffff; } .resend{ color: rgb(14, 14, 196); padding: 5px; } .s:hover{ cursor: pointer; background-color:gray; color: rgb(243, 237, 237); border-radius: 5px; } </style> </head> <body> <?php $code=""; $err=""; $error=""; if(($_SERVER["REQUEST_METHOD"]=="GET" && $_SESSION['xyz'] === 'xyz') || isset($_POST['verify']) || isset($_POST['resend'])) { unset($_SESSION["xyz"]); if($_SERVER["REQUEST_METHOD"] ==="POST") { if(isset($_POST['verify'])) { if(empty($_POST['code'])) { $err="Enter the code!"; } else { $code=$_POST['code']; if(password_verify($code,$_SESSION['code'])) { $name=$_SESSION['name']; $email=$_SESSION['email']; $tel=$_SESSION['tel']; $dob=$_SESSION['dob']; $password=$_SESSION['password']; $age_category=$_SESSION['age_category']; require_once('./all_utils/connection.php'); $sql="INSERT INTO identity_table(name,email,password,tel,dob,age_category) VALUES ('$name','$email','".$password."','$tel','$dob','$age_category')"; if(mysqli_query($conn,$sql) === TRUE) { unset($_SESSION["name"]); unset($_SESSION["password"]); unset($_SESSION["dob"]); unset($_SESSION["tel"]); unset($_SESSION["age_category"]); header("location:welcome/welcome.php"); } else { $err="Error! Something went wrong"; } } else { $err="Incorrect code!"; } } } elseif(isset($_POST['resend'])) { require_once('./all_utils/mail.php'); $error="OTP has been sent again!"; } } } else{ header("location:signup.php"); } ?> <div class="cont"> <h2> Email Verification</h2> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST"> <label for="verification">Enter the 5 digit code</label> <br/> <p> Didn't got the mail? Please check your spam folder </p> <input type="text" name="code" placeholder="Eg. 12345" value="<?php echo $code; ?>"> <br/> <div class="error"><?php echo $err; ?></div> <div class="resend"><?php echo $error;?></div> <input type="submit" name="resend" class="s" id="left" value="Resend OTP"> <input type="submit" name="verify" class="s" id="right" value="Verify"> </form> </div> </body> </html>
This is my signup.php code <?php session_start(); if(!empty($_SESSION['email'])) { require_once('./all_utils/connection.php'); $query="SELECT * FROM identity_table WHERE email='".$_SESSION['email']."'"; $result=mysqli_query($conn,$query); if(mysqli_fetch_assoc($result)) { header("location:welcome/welcome.php"); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SignUp - Kanha Stories</title> <style> * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; display: flex; align-items: center; background-color: #ff9d00; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1600 800'%3E%3Cg stroke='%23000' stroke-width='66.7' stroke-opacity='0' %3E%3Ccircle fill='%23ff9d00' cx='0' cy='0' r='1800'/%3E%3Ccircle fill='%23f27d00' cx='0' cy='0' r='1700'/%3E%3Ccircle fill='%23e55f00' cx='0' cy='0' r='1600'/%3E%3Ccircle fill='%23d84400' cx='0' cy='0' r='1500'/%3E%3Ccircle fill='%23cb2c00' cx='0' cy='0' r='1400'/%3E%3Ccircle fill='%23bf1600' cx='0' cy='0' r='1300'/%3E%3Ccircle fill='%23b20300' cx='0' cy='0' r='1200'/%3E%3Ccircle fill='%23a5000e' cx='0' cy='0' r='1100'/%3E%3Ccircle fill='%2398001c' cx='0' cy='0' r='1000'/%3E%3Ccircle fill='%238b0027' cx='0' cy='0' r='900'/%3E%3Ccircle fill='%237e0030' cx='0' cy='0' r='800'/%3E%3Ccircle fill='%23710037' cx='0' cy='0' r='700'/%3E%3Ccircle fill='%2364003b' cx='0' cy='0' r='600'/%3E%3Ccircle fill='%2358003c' cx='0' cy='0' r='500'/%3E%3Ccircle fill='%234b003a' cx='0' cy='0' r='400'/%3E%3Ccircle fill='%233e0037' cx='0' cy='0' r='300'/%3E%3Ccircle fill='%23310030' cx='0' cy='0' r='200'/%3E%3Ccircle fill='%23210024' cx='0' cy='0' r='100'/%3E%3C/g%3E%3C/svg%3E"); background-attachment: fixed; background-size: cover; overflow-x: hidden; } .cont { color: #ffffff; width: 500px; margin: auto; } h2 { color: #ffffff; text-align: center; padding: 1.5px; } .error { text-align: center; padding: 20px; font-size: 1rem; color: rgb(233, 76, 76); } form { font-size: 1.2rem; /* width: 40%; */ /* margin: auto; */ } .in{ margin: 5px 0; } input { border: 2px solid white; padding: 10px; margin: 5px 0; font-size: 1rem; width: 100%; } input:hover { border: 2px solid rgb(228, 81, 81); cursor: text; } p,a{ text-align: center; font-size: 1rem; } a{ color: deepskyblue; font-size:20px; } #s{ text-decoration:none; border-radius: 12px; } #s:hover { cursor: pointer; } a { text-decoration: none; } @media only screen and (max-width: 600px){ .cont{ width: 300px; } .error,input{ font-size: 0.8rem; } } @media only screen and (max-width: 400px){ .cont{ width: 70%; } h2{ font-size: 1.3rem; } a,p{ font-size: 0.7rem; } label{ font-size: 1.0rem; } input{ padding: 4px; } } </style> </head> <body> <?php $name=""; $email=""; $tel=""; $dob=""; $err=""; $name_err=""; $email_err=""; $tel_err=""; $dob_err=""; $password_err=""; if($_SERVER["REQUEST_METHOD"]=="POST") { if(isset($_POST['signup'])) { if(empty($_POST['name']) || empty($_POST['dob']) || empty($_POST['tel']) || empty($_POST['email']) || empty($_POST['password'])) { if(empty($_POST['name'])) { $name_err="Name is required!"; } else{ $name=$_POST['name']; } if(empty($_POST['email'])) { $email_err="Email is required!"; } else{ $email=$_POST['email']; } if(empty($_POST['tel'])) { $tel_err="Contact Number is required!"; } else{ $tel=$_POST['tel']; } if(empty($_POST['dob'])) { $dob_err="D.O.B is required!"; } else{ $dob=$_POST['dob']; } if(empty($_POST['password'])) { $password_err="Password is required!"; } } else { $today = new DateTime(date('m.d.y')); $dob = new DateTime($_POST['dob']); $diff1 = $today->diff($dob); $age = $diff1->y; if($age > 15 || $age <3) { $dob = $_POST['dob']; $dob_err = "Age criteria not satisfied , child's age must be between 3-15 years"; } else { require_once("./all_utils/connection.php"); $email=$_POST['email']; $query="SELECT * FROM identity_table WHERE email='".$email."'"; $result=mysqli_query($conn,$query); if(mysqli_fetch_assoc($result)) { $err="Email alredy registered!"; $name=$_POST['name']; $email=$_POST['email']; } else { if($age < 7) { $_SESSION['age_category'] = '1'; } else { $_SESSION['age_category'] = '2'; } $_SESSION['name']=$_POST['name']; $_SESSION['email']=$_POST['email']; $_SESSION['password'] = password_hash($_POST['password'],PASSWORD_DEFAULT); $_SESSION['tel']=$_POST['tel']; $_SESSION['dob']=$_POST['dob']; $_SESSION['xyz']='xyz'; require_once("all_utils/mail.php"); header("location:conf.php"); } } } } } ?> <div class="cont"> <h2>SignUp - Kanha Stories</h2> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST"> <span class="error"><?php echo $err; ?></span> <br/> <label for="name">Name</label><br /> <input type="text" name="name" placeholder="Enter your name" value="<?php echo $name; ?>"> <span class="error"><?php echo $name_err; ?></span> <br/> <label for="email">Email</label><br /> <input type="email" name="email" placeholder="Enter your Email ID" value="<?php echo $email; ?>"> <span class="error"><?php echo $email_err;?></span> <br/> <label for="tel">Mobile Number</label><br /> <input type="tel" name="tel" placeholder="Enter Mobile Number" value="<?php echo $tel; ?>"> <span class="error"><?php echo $tel_err;?></span> <br/> <label for="date">D.O.B. of Child (Click on Calander icon)</label><br /> <input type="date" name="dob" placeholder="Enter date of birth " value="<?php echo $dob;?>"> <span class="error"><?php echo $dob_err;?></span> <br/> <label for="password">Password</label><br /> <input type="password" name="password" placeholder="Enter your Password"> <span class="error"><?php echo $password_err; ?></span> <br/> <div class="sub"> <input type="submit" name="signup" id="s" placeholder="Submit"><br /> </div> </form> <p>Already registered? <a href="./login.php">log in here</a></p> </div> </body> </html>
I don't know what I can do now , Please try to give me the solutions as soon as possible. Thanks New to classes, basic understanding of procedural. I am trying to echo rows from the data base using PDO. Here is the code: Code: [Select] <div id="admin"> <form method="POST" action="categoryAdmin.php"> <table> <tr><th bgcolor="#EEEEEE">Cat Id</th> <th bgcolor="#EEEEEE">Title</th> <th bgcolor="#EEEEEE">Description</th> </tr> <?php global $dbh; $sql = "SELECT * FROM categories"; $sth = $dbh->prepare($sql); $sth-> execute(); print_r($sth); $result = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($result); while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {echo "<tr><td>$row[0]<td><td>$row[1]<td><td>$row[2]<td><tr>\n";} ?> <tr><td><input type="text" name="CatId" size="15" maxlength="10"></td> <td><input type="text" name="CatTitle" size="40" maxlength="130"></td> <td><input type="text" name="CatDesc" size="45" maxlength="200"></td> </tr> </table> <input type="hidden" name="addRecord" value="1"> <input type="submit" name="submit" value="Add Category"> </div> print_r($sth); shows: PDOStatement Object ( [queryString] => SELECT * FROM categories ) print_r($result); shows: Array ( => Array ( [categoryId] => Fitness [title] => Sholder Guy [description] => Fix that sholder and more ) ) fatal error: Call to a member function fetchAll() on a non-object in /home/... the line in question is the while loop. I am not sure what to pass it with reguards to PDO. Thanks - AL Hi Guys Trying to get xml elements to display in a html table using the following code Code: [Select] <?php session_start(); include_once('includes/connect_inc.php'); $file="https://www.cdlvis.com/lookup/getxml?username=username&mode=test&key=password&vrm=".$_POST['veh_reg'].""; $dom=new DOMdocument(); $dom->load($file); $xml=simplexml_import_dom($dom); ?> and Code: [Select] <form name="vehicle_details" method="post" action="add_vehicle.php"> <table> <tr> <td>Registration Number:</td><td><input name="reg_num" type="text" value="<?php echo $xml->result[0]->vrm;?>" readonly="true" /></td></tr> <tr> <td>Make:</td><td><input name="make" type="text" value="<?php echo $xml->result[0]->make;?>" readonly="true" /></td></tr> <tr> <td>Model:</td><td><input name="model" type="text" value="<?php echo $xml->result[0]->model;?>" readonly="true" /></td></tr> <tr> <td>Date of Manufactu </td><td><input name="date_man" type="text" value="<?php echo $xml->result[0]->date_manufactured;?>" readonly="true" /></td></tr> <tr> <td>Date of First Registration:</td><td><input name="date_reg" type="text" value="<?php echo $xml->result[0]->first_registered;?>" readonly="true" /></td></tr> <tr> <td>Colour:</td><td><input name="colour" type="text" value="<?php echo $xml->result[0]->colour;?>" readonly="true" /></td></tr> <tr> <td>Body Style:</td><td><input name="body" type="text" value="<?php echo $xml->result[0]->body;?>" readonly="true" /></td></tr> <tr> <td>Number of Doors:</td><td><input name="doors" type="text" value="<?php echo $xml->result[0]->doors;?>" readonly="true" /></td></tr> <tr> <td>Engine Size:</td><td><input name="engine_size" type="text" value="<?php echo $xml->result[0]->engine_size;?>" readonly="true" /></td></tr> <tr> <td>Fuel Type:</td><td><input name="fuel_type" type="text" value="<?php echo $xml->result[0]->fuel;?>" readonly="true" /></td></tr> <tr> <td>Gearbox Type:</td><td><input name="gearbox" type="text" value="<?php echo $xml->result[0]->gearbox_type;?>" readonly="true" /></td></tr> <tr> <td>Previous Keepers:</td><td><input name="keepers" type="text" value="<?php echo $xml->result[0]->previous_keepers;?>" readonly="true" /></td></tr> <tr> <td>BHP:</td><td><input name="bhp" type="text" value="<?php echo $xml->result[0]->smmt_power_bhp;?>" readonly="true" /></td></tr> <tr> <td>Emissions:</td><td><input name="co2" type="text" value="<?php echo $xml->result[0]->smmt_co2;?>" readonly="true" /></td></tr> <tr> <td><input name="try_again" type="button" value="Try Again" /></td><td><input name="submit" type="submit" value="Next Stage" /></td></tr> </table> </form> What have I done wrong? Keep getting this error from line 19 (Notice: Trying to get property of non-object in /clientdata/zeus-dynamic-1/s/o/blahblah/www/tyson/onion.php on line 18)... have no idea how to get rid of it. Do I have to use isset? If so.. where??? (obviously I've replaced site address with website) Code: [Select] include('simple_html_dom.php'); $story = array(); getArticles('website'); function getArticles($page) { global $story, $desc, $read; $html = new simple_html_dom(); $html->load_file($page); $items = $html->find('div[id=story_content]'); foreach($items as $post) { $story[] = array($post->children(0)->plaintext, $post->children(2)->next_sibling()->innertext, $post->children(4)->innertext); } } $i = 0; foreach($story as $item) { $syurl = str_replace('href="', 'href="http://website', $item[2]); echo '<p class="storytitle">' . $item[0] . '</p>'; echo '<p class="storyexcerpt">' . $item[1] . '</p>'; echo '<p class="storyread">' . $syurl . '</p>'; if (++$i == 3) break; } Any ideas? This line is causing the issue: $story[] = array($post->children(0)->plaintext, $post->children(2)->next_sibling()->innertext, $post->children(4)->innertext); Likewise, it does post the 3 storys below the 2 error lines...? Hi,
This code works (and correctly shows just one result in my view);
$people = DB::table('people')->where('id', '=', $person_id)->get();But this one doesn't; $people = DB::table('people')->where('id', $person_id)->first();And produces the error; Trying to get property of non-object (View: /media/sf_sandbox/health/app/views/agreement/display.blade.php)The `people` table just has a few fields of information on the individual with a primary key called `id`. I followed the Laravel guide on select statements. I don't understand what the error is trying to tell me and I don't get why that second statement is wrong. What's so wrong about it? I just want to understand Laravel/Objects better.... Thanks Hey, I'm trying to create an object oriented webpage, with just some basic features, like creating a user, logging in, admin restricted pages. However I'm stuck at this point. This is my code: class_user.php Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php"; ?> <?php class User { private $database; public function __construct(MySqlDatabase $database) { //Type Hinting $this->database = $database; } public function find_all() { $result = $this->database->db_query("SELECT * FROM users"); return $result; } public function find_by_id($id=1) { $result = $this->database->db_query("SELECT * FROM users WHERE id={$id}"); $final = mysqli_fetch_array($result); return $final; } } ?>class_database.php Code: [Select] <?php include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php"; include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php"; ?> <?php class MySqlDatabase extends MySQLi { function __construct() { //Check if constants are missing if (defined(!DB_USERNAME) || defined(!DB_SERVER) || defined(!DB_PASSWORD) || defined(!DB_NAME)) { die("One or more of the database constants are missing: " . mysqli_errno); } //Establish connection if constants are present using the parent class parent::__construct(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); //Echo error message if connection has failed if ($this->connect_errno) { die("Database connection has failed: " . $this->connect_errno); } } public function db_query($sql) { $result = mysqli_query($this->connection, $sql); if (!$result) { die("Database query failed: " . $this->errno); } return $result; } public function query_prep($value) { $result = mysqli_real_escape_string($this->connection, $value); if (!$result) { die("Preparing query failed: " . $this->errno); } return $result; } } ?>Calling externally: Code: [Select] <?php $database = new MySqlDatabase(); $user = new User($database); $found = $user->find_all(); ?>This is the error I'm getting: Quote Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\includes\class_database.php on line 28 Database query failed: 0 I've tried everything I can come up with, but still I'm stuck at this error. I just ran into grief while trying to store a DateTime object in the SESSION variable. When I tried to use the stored value I got the error message "The DateTime object has not been correctly initialized by its constructor." I initially assumed that objects can't be stored in SESSION because there's no way to serialize and deserialize them for storage between scripts. But I've found posts by other people who have done this with without problems. If it works for others, why isn't it working for me? Is there something special about the DateTime class that prevents the PHP engine from serializing it? Here's a little script that demonstrates the problem (in PHP 5.2.5 under Windows XP): Code: [Select] <?php session_start(); if ( key_exists( 'd', $_SESSION ) ) { $d = $_SESSION['d']; echo "<br/>The value of 'd' is " . $d->format('m/d/Y'); } else { echo "'d' has no value yet."; } $d = new DateTime('2011-08-01'); $_SESSION['d'] = $d; $e = $_SESSION['d']; echo "<br/>The value of 'd' has been set to " . $e->format('m/d/Y'); ?> The first time the script is run it does not display "The value of 'd' is..." because $_SESSION['d'] does not exist. It sets the value, then retrieves it intact and displays it. The second time the script is run it tries to retireve the value but apparently gets an invalid one and displays the error. Then it sets, retrieves, and displays the value again. I'm using PHP 5.2 Server and Simple HTML DOM 1.5. This script scrape or extract data from a football site, its fully working on PHP 5.9 Server but I need to know how I can fix it for PHP 5.2 server. Can someone give me a hint on how can I fix the error? Thanks in advance. My PHP 5.2 Server script output shows: ++++++++++++++++ Object id #599 Object id #604 Object id #609 Object id #614 Object id #619 Object id #627 Object id #632 Object id #637 Object id #642 Object id #647 Object id #655 Object id #660 Object id #665 Object id #670 Object id #675 Object id #683 Object id #688 Object id #693 Object id #698 Object id #703 Object id #711 Object id #716 Object id #721 Object id #726 Object id #731 ++++++++++++++++ while PHP 5.9 Server says ++++++++++++++++ Rk Player Team POS OPPONENT 1 Aaron Rodgers GB QB at CAR 2 Tom Brady NE QB vs. SD 3 Matt Schaub HOU QB at MIA 4 Michael Vick PHI QB at ATL ++++++++++++++++ I did applied the bug solution listed on https://sourceforge.net/tracker/index.php?func=detail&aid=3107230&group_id=218559&atid=1044037 but it is still not working. It says: ++++++++++++++++ Details: I get compiler errors in PHP 5.2 when using this as an object. The offending lines are 609 and 940, which both contain this construct: if ($this->size>0) $this->char = $this->doc[0]; This tries to get the first character of $this->doc, but PHP 5.2 sees it as trying to access it as an array. It's easily fixed by this: if ($this->size>0) $this->char = substr($this->doc, 0, 1); Or you could probably use chr(ord($this->doc)) as well. Either way solves the compile error without changing functionality. ++++++++++++++++ Here are my codes: Code: [Select] <?php # don't forget the library include('simple_html_dom.php'); # this is the global array we fill with article information $articles = array(); $source = 'http://www.athlonsports.com/columns/winning-game-plan/fantasy-football-qb-rankings'; # passing in the first page to parse, it will crawl to the end # on its own getArticles($source); function getArticles($page) { global $articles, $descriptions; $html = new simple_html_dom(); $html->load_file($page); //$items = $html->find('div[class=preview]'); $items = $html->find('tbody tr'); foreach($items as $post) { # remember comments count as nodes /*$articles[] = array($post->children(3)->outertext, $post->children(6)->first_child()->outertext);*/ $articles[] = array($post->children(0), $post->children(1), $post->children(2), $post->children(3), $post->children(4)); } # lets see if there's a next page if($next = $html->find('a[class=nextpostslink]', 0)) { $URL = $next->href; echo "going on to $URL <<<\n"; # memory leak clean up $html->clear(); unset($html); getArticles($URL); } } ?> <html> <head> </head> <body> <? echo "Source: " . $source; ?> <table cellpadding="5" cellspacing="0" border="0"> <?php foreach($articles as $item) { echo "<tr>"; echo "<td>" . $item[0] . "</td><td>" . $item[1] . "</td><td>" . $item[2] . "</td>"; echo "<td>" . $item[3] . "</td><td>" . $item[4] . "</td>"; echo "<tr>"; } ?> </table> </body> </html> I made a small script and it says that my database object isn't an object. I connect to my pdo database via: <?php try { $db = new PDO("mysql:host=localhost;dbname=database", "root", "root"); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } ?> The error I get is Code: [Select] Notice: Undefined variable: db in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 Fatal error: Call to a member function query() on a non-object in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 here's where the error is $grabber = $db->query('SELECT * WHERE user_id =' . $userid); $grabber->setFetchMode(PDO::FETCH_OBJ); while ( $row = $grabber->fetch() ){ $display = '<div>Task Name: ' . $row->name .'</div>'; $display .= '<div>Task Details: <p>'. $row->details .'</p></div>'; //$display .= '<div>'. $this->checkifDone($row->task_status) .'</div>'; $display .= '<div>Task Due: '. $row->task_due . '</div>'; echo $display; } could anyone tell me where this issue is originating I followed a fairly simple tutorial that didn't seem to work. Thanks! I'm new to coding and prepared statements.
I'm getting: For this: <?php include "db_connect.php"; if(isset($_POST['UserID'])){ $stmt = $con -> prepare('UPDATE UserList SET Status = ?, FirstName = ?, LastName = ?, Username = ?, Email = ?, Department = ?, Manager = ?, WHERE UserID = ?'); $stmt -> bind_param('isssssss', /* Line 17 */ $_POST['Status'], $_POST['FirstName'], $_POST['LastName'], $_POST['Username'], $_POST['Email'], $_POST['Department'], $_POST['Manager'], $_POST['UserID']); $stmt->execute(); } Thank you in advance for helping. can anyone tell me why im getting this error? Fatal error: Call to a member function fetchrow() on a non-object code being used..... Code: [Select] $comment_query = mysql_query("SELECT * FROM `comments` where video_id='$video[0]' ORDER BY='desc' LIMIT='30'"); while($comments = $comment_query->fetchrow()) { Code: [Select] <?php class OnlineStore { private $DBConnect = NULL; private $storeID = ""; private $inventory = array(); private $shoppingCart = array(); function __construct() { include("inc_OnlineStoreDB.php"); $this->DBConnect = $DBConnect; } function __destruct() { if (!$this->DBConnect->connect_error) $this->DBConnect->close(); } public function setStoreID($storeID) { if ($this->storeID != $storeID) { $this->storeID = $storeID; $SQLstring = "SELECT * FROM inventory " . " where storeID = 'jw" . $this->storeID . "'"; $QueryResult = $this->DBConnect->query($SQLstring); if ($QueryResult === FALSE) { $this->storeID = ""; } else { $this->inventory = array(); $this->shoppingCart = array(); while (($Row = $QueryResult->fetch_assoc()) !== NULL) { $this->inventory[$Row['productID']] = array(); $this->inventory[$Row['productID']]['name'] = $Row['name']; $this->inventory[$Row['productID']]['description'] = $Row['description']; $this->inventory[$Row['productID']]['price'] = $Row['price']; $this->shoppingCart[$Row['productID']] = 0; } } } } public function getStoreInformation() { $retval = FALSE; if ($this->storeID != "") { $SQLstring = "SELECT * FROM store_info " . " WHERE storeID = '" . $this->storeID . "'"; $QueryResult = @$this->DBConnect->query($SQLstring); if ($QueryResult !== FALSE) { $retval = $QueryResult->fetch_assoc(); } } return($retval); } public function getProductList() { $retval = FALSE; $subtotal = 0; if (count($this->inventory) > 0) { echo "<table width='100%'>\n"; echo "<tr><th>Product</th><th>Description</th>" . "<th>Price Each</th><th># in Cart</th>" . "<th>Total Price</th><th> </th></tr>\n"; foreach ($this->inventory as $ID => $Info) { echo "<tr><td>" . htmlentities($Info['name']) . "</td>\n"; echo "<td>" . htmlentities($Info['description']) . "</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $Info['price']); echo "<td class='currency'>" . $this->shoppingCart[$ID] . "</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $Info['price'] * $this->shoppingCart[$ID]); echo "<td><a href='" . $_SERVER['SCRIPT_NAME'] . "?PHPSESSID=" . session_id() . "&ItemToAdd=$ID'>Add " . " Item</a></td>\n"; $subtotal += ($Info['price'] * $this->shoppingCart[$ID]); } echo "<tr><td colspan='4'>Subtotal</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $subtotal); echo "<td>$nbsp;</td></tr>\n"; echo "</table>"; $retval = TRUE; } return($retval); } public function addItem() { $ProdID = $_GET['ItemToAdd']; if (array_key_exists($ProdID, $this->shoppingCart)) $this->shoppingCart[$ProdID] += 1; } } ?> having an issue to where nothing is appearing on the page and getting the Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\PHP\Chapter.10\class_OnlineStore.php on line 24 HERE IS THE MAIN PAGE Code: [Select] <?php session_start(); require_once("class_OnlineStore.php"); $storeID = "COFFEE"; $storeInfo = array(); if (class_exists("OnlineStore")) { if (isset($_SESSION['currentStore'])) $Store = unserialize($_SESSION['currentStore']); else { $Store = new OnlineStore(); } $Store->setStoreID($storeID); $storeInfo = $Store->getStoreInformation(); } else { $ErrorMsgs[] = "The OnlineStore class is not available!"; $Store = NULL; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $storeInfo['name']; ?></title> <link rel="stylesheet" type="text/css" href="<?php echo $storeInfo['css_file']; ?>" /> </head> <body> <h1><?php echo htmlentities($storeInfo['name']); ?></h1> <h2><?php echo htmlentities($storeInfo['description']); ?></h2> <p><?php echo htmlentities($storeInfo['welcome']); ?></p> <?php $Store->getProductList(); $_SESSION['currentStore'] = serialize($Store); ?> </body> </html> I HAVE REVIEWED IT OVER AND OVER AGAIN AND I CANT SEE THE PROBLEM. MAYBE SOMEONE FROM THE OUTSIDE CAN HELP OUT. Hey all. I am trying to make a mod for our fantasy football site but keep getting an error. Fatal error: Call to a member function Execute() on a non-object in C:\Inetpub\wwwroot\phpffl\program_files\autorun\general\top_team.php on line 8. Here is the code. <?php global $PHP_SELF, $DB; $leagues_ID='1'; $week='2'; $week_ID=$week -1; $game_ID=$week_ID; $sql="select ID, team_name from teams where leagues_ID='$leagues_ID';"; [b] $teams_rs=$DB->Execute($sql);[/b] while (!$teams_rs->EOF) { $top_team_ID=$teams_rs->fields('ID'); $top_team_name=$teams_rs->fields('team_name'); $top_team_points=get_total_points_game($top_team_ID, $week_ID, $week_ID, $leagues_ID); //echo $top_team_points." "; $top_team_points_array[$top_team_name]=$top_team_points; $teams_rs->MoveNext(); } $top_scoring_team_ID=""; $top_scoring_team_name=""; $top_scoring_points=""; foreach(array_keys($top_team_points_array) as $key) { if ($top_team_points_array[$key] > $top_scoring_points) { $top_scoring_points=$top_team_points_array[$key]; //$top_scoring_team_ID=$top_team_ID; $top_scoring_team_name=$key; } } $sql="insert into total_scores (team_ID, teams_name, week_id, total_score, leagues_ID) values('$top_team_ID', '$top_scoring_team_name', '$week_ID', '$top_scoring_points', '$leagues_ID');"; $rs=$DB->Execute($sql); echo "<br>"; echo "<br>"; echo "Weekly Top Scoring Team for Week $week_ID is: $top_scoring_team_name with a score of $top_scoring_points points!"; echo "<br>"; echo "<br>"; //print_r ($top_team_points_array); echo "<br>"; echo "<br>"; $weekly_top_score=max($top_team_points_array); ?> I have a function in the global file looks like this. /************** BEGIN ADDITIONAL FUNCTIONS **************************/ function get_top_scoring_teams() { global $PHP_SELF, $DB, $PHPFFL_IMAGE_PATH; $sql="select * from total_scores order by week_ID DESC limit 1;"; $teams_rs=$DB->Execute($sql); while (!$teams_rs->EOF) { $team_ID=$teams_rs->fields('team_ID'); $team_name=$teams_rs->fields('teams_name'); $team_points=$teams_rs->fields('total_score'); $week_ID=$teams_rs->fields('week_ID'); echo "The Top Scoring Team for <strong>Week $week_ID</strong> was <br><img src='{$PHPFFL_IMAGE_PATH}team_logos_standings/$team_ID.gif'><br> <strong>$team_name</strong> with a score of <strong>$team_points</strong> points. <hr>"; $teams_rs->MoveNext(); } } /************** BEGIN ADDITIONAL FUNCTIONS**************************/ Any one see what the issue might be? I am running this on a windows 2003 server with iis 6 php 5.3 and mysql 5.1.5 Any help would be appreciated. Thanks Hitster4 hi, very strange issue. when I create test e-mail or I will forward the specific e-mail, the script works correctly - saves attachment into server disk. now, when I configure to check another mailbox, it gives me error: Num Messages 11 Fatal error: Cannot use object of type stdClass as array in /test/emailattach/index.php on line 34 index.php: Code: [Select] <?php $mbox = imap_open("{mail.server.com:143}", "email@email", "XXX") or die('Cannot connect to mail: ' . imap_last_error()); // make connection with mailbox and check # messages if ($hdr = imap_check($mbox)) { echo "Num Messages " . $hdr->Nmsgs ."\n\n<br><br>"; $msgCount = $hdr->Nmsgs; } else { echo "failed"; } $overview=imap_fetch_overview($mbox,"1:$msgCount",0); $size=sizeof($overview); // get message info for($i=$size-1;$i>=0;$i--) { $val=$overview[$i]; $msg=$val->msgno; $from=$val->from; $date=$val->date; $subj=$val->subject; $seen=$val->seen; $from = ereg_replace("\"","",$from); // Check for attachements and store them $struct = imap_fetchstructure($mbox,$msg); $contentParts = count($struct->parts); if ($contentParts >= 2) { for ($ix=2;$ix<=$contentParts;$ix++) { $att[$ix-2] = imap_bodystruct($mbox,$msg,$ix); } for ($k=0;$k<sizeof($att);$k++) { if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") { if ($att[$k]->parameters[1]->value != "") { $FileName[$k] = $att[$k]->parameters[1]->value; $FileType[$k] = strrev(substr(strrev($FileName[$k]),0,4)); } } elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") { $FileName[$k] = $att[$k]->parameters[0]->value; $FileType[$k] = strrev(substr(strrev($FileName[$k]),0,4)); $fileContent = imap_fetchbody($mbox,$msg,$file+2); $fileContent = imap_base64($fileContent); $localfile = fopen("$FileName[$k]","w"); fputs($localfile,$fileContent); fclose($localfile); } } } } imap_close($mbox); ?> Could there be some encoding issue? with thanks, Margus Hello everyone.
please I have problem with printing out a value from inside an array of a nested json. ive tried several ways its always returns "index not define". $valr= "https://ice3.com/api/v1/orderbook/ticker"; ////////////////////////////source $valrGet = file_get_contents($valr); $valrD = json_decode($valrGet, true); $valrSell = ["ask"] ["price"]; Here is the structure of the json from the source : {"errors":false,"response":{"entities":[{"pair_id":3,"pair_name":"BTC\/ZAR","ask":{"price":"179382.54","amount":"0.05357142"},"bid":{"price":"177229.4286563","amount":"0.0011"}},{"pair_id":4,"pair_name":"BTC\/NGN","ask":{"price":"8890000.00","amount":"0.10"},"bid": my target is to output the value of ("price") from "pair_name" BTC\/ZAR please help. Thanks in advance here is my php code. i want to remove the attribute of a tag and then add a new attribure to the tag. simply i want attribute validation. but this code gives me the following error. "Fatal error: Call to a member function getAttributeNode() on a non-object in D:\wamp\www\ReadXml\new.php on line 35" <?php $xml = new DOMDocument(); $doc->recover = true; $xml->load('test.xml'); $node = $xml->getElementsByTagName('*'); $nodename = ""; $node_name = array(); $att = ""; $attr_name = ""; $attr_value = ""; foreach($node as $value) { echo "<HTML><Head>"; echo "<title> Getting Attribute Example</title>"; echo "</Head><body><B>"; echo "Node Name is :".$value->nodeName; echo "<br /><br /></B></body></HTML>"; $nodename = $value->nodeName; $node_name = $xml->getElementsByTagName('$nodename')->item(0); echo $nodename; $att = $node_name->getAttributeNode('name'); //Line No 35 echo "<HTML><Head>"; echo "<title> Getting Attribute Example</title>"; echo "</Head><body><B>"; echo "Node Name is :".$att->name; echo "<BR>Attribute Value is :".$att->value; echo "<br /><br /></B></body></HTML>"; $attr_name = $att->name; $attr_value = '"' . $att->value . '"'; $nodename->removeAttributeNode('$attr_name'); $nodename->setAttributeNode(new DOMAttr('$attr_name', 'hello')); $nodename->setAttribute(new DOMAttr('$attr_name', '$attr_name')); $xml->save('temp2.xml'); } ?> Hello guys I'm pulling out my last remaining hairs with this PHP problem. I'm not really good at PHP but I'm trying to do some changes to a script as instructed by the developer, but apparently I got some wrong instructions. The error I get is: Fatal error: Call to a member function postage_country_display() on a non-object in file.php on line 34 I've been searching the web high and low and can't seem to find a solution. Does anyone have a hint at what might be wrong? Here is the code that's causing the problem and the class. Code: Code: [Select] $template->set('items_id', intval($_REQUEST['items_id'])); $item_details = $db->get_sql_row("SELECT * FROM " . DB_PREFIX . "items WHERE items_id='" . intval($_REQUEST['items_id']) . "'"); $unCountryPrice = unserialize(stripslashes($db->add_special_chars($item_details['country_postage']))); // print_r($unCountryPrice); $postageCountry = $item->postage_country_display($unCountryPrice,$item_details['currency']); $template->set('postageCountry', $postageCountry); $template->set('item_details', $item_details); And here is the class: Code: [Select] function postage_country_display($unCountryPrice,$currency) { if (is_array($unCountryPrice)) { $postageCountry = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"> "; $fees = new fees(); while (list($k,$v)= each($unCountryPrice)){ $cQueyr = $this->query("SELECT a.name as name1,b.name as name2 FROM " . DB_PREFIX . "countries a LEFT JOIN " . DB_PREFIX . "countries b ON (a.parent_id = b.id) WHERE a.id = '". $k ."'"); $cRow = $this->fetch_array($cQueyr); $postageCountry.="<tr><td>". ($cRow['name2']==""?$cRow['name1']:$cRow['name2'].' > '.$cRow['name1']) ."</td><td> ".$currency.' '.number_format($v,2)."</td></tr>"; } $postageCountry.="</table>"; } return $postageCountry; |