PHP - What Is The Scope Of An Object Created Within A Class Constructor?
Long story short, I have a class that does some data verification and session management. In order to do some of this verification, it needs a database connection. I am using the MDB2 class;
here is a sample of the constructor's code: this is a snippet of code from My Class. // FUNCTIONS function __construct() { /* other code here */ // set up our datbase connection global $dsn; // must use global as to include the one *from* the settings.php include $mdb2 =& MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage()); } echo("SESSION CLASS: if you see this, then we're goood!"); // some very crude debugging, please ignore this! } Now, i have another function within this same class: public static function data_validateUserName($safeUserName){ // build the query $q = "SELECT uName FROM Users WHERE username = '$safeUserName'"; $result = $this->$mdb2->query($q); if($result->numRows() >= 1){ // there is 1 or more hits for a username, it is not available! return false; } else if ($result->numRows() < 1){ // there is less than 1 row with that username, we're golden! return ture; } } Inside the constructor, i have correctly set up a MDB2 object. I was able to run some queries and other things on it *inside* the constructor. Because of this, i know that it's settings are correct and it is fully working. However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist. Now, i tried searching here, and didn't get much help, so apologies. If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it... Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here. Thanks for your time, all. ***** EDIT ****** I've thought about doing it another way: Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self. Would this be better / more secure / more efficient?! Similar TutorialsIf a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Hi, I need some help with php using class and constructor, this is stuff I am familiar with with Java but not in PHP, so I can't get the code to run. please see code below: ================ Code: [Select] <?php $array1=array(""); $array2=array(""); $binary=1; class Foobar { /*Toy FCN that will append "dog" to 1 and "cat" to -1*/ //param numRuns is how many times to run this FCN function putInProperArray($numRuns) { for($i=0;$i<$numRuns;$i++) { if($binary==1) $array1=$array1." dog <br />"; else if($binary==-1) $array2=$array2." cat <br />"; $binary*=-1; } } $fooBar=new Foobar(); $fooBar->putInProperArray(3); } ?> I just want it to store appended "dog" or "cat" string to array1 or array2, just a random function I made up. Please help, thanks. I am calling my class constructor with the following code class controller{ function _construct($name,$pass){ session_start(); get_model_class($name, $pass); echo "I\'m in controller"; } } function get_model_class($username, $password){ $my_model = new model(); $my_model->check_users($username,$password); } $username = $_POST['username']; $password = $_POST['password']; echo "in controller.php"; $newUser = new controller($username,$password); but it is not entering the constructor So I have this class: Code: [Select] <?php class page { private $title; function __construct(){ //note: This code snippet (below) does not appear to be having the desired effect of //running the PHP code on page declared by p if(!isset($_GET['p'])) : include("../content/home.php"); else : include("../content/{$_GET['p']}.php"); endif; /////////////////////////////////////////////// } public function setTitle($t) { $this->title=$t; }?> and I need the following from the content page (the page declared by $_GET['p']) to be ran in the constructor: Code: [Select] <?php global $page; $page->setTitle("About Us"); ?> this is in order to set the page title, so I can use it elsewhere. I hope my explanation (although fairly vague), is somewhat clear. Any help on this? I was told that using <<<EOF would be a potential requirement? but I am completely unfamiliar with that method. Hello there
After a few years of spending less and less time coding, I've got a lot of catching up to do. Back when I left I usually would run without classes. Now this is a big deal for me today.
I do understand the concept of classes and already did some working models, mostly from my learning process.
Now here is what is bothering me:
<?PHP class database { // Variables public $test; // Constructor public function __construct() { $test = "4"; } // Functions // public function test() { var_dump($this->test); } } $test = new database; $test->test(); ?>Wether I run this script on itself, nor through another file, this does work. What i get is: NULL The constructor does run, I did an echo inside it. Also it does not matter if the variable is public, private or protected - it will be always NULL. Error_reporting is on E_ALL, does not show any errors. What have I overlooked? Using PHP Version 5.2.13 My question: How do I access a class and it's methods from an included file? I have an Index.php page that calls two methods: <?php get_header(); ?> <?php get_footer(); ?> and it creates a class in an include file <?php include_once($_SERVER['DOCUMENT_ROOT'].'/includes/common.html');?> $site = new WebSite($site_name); // Creates a bunch of properties, defines some methods, etc... $site->initialize(); <?php get_header(); ?> ends up including a another file (header.php) <?php get_header(); ?> ends up including a another file (footer.php) All calls in Index.php to methods in my class work. ie <?php $site->display_section('column'); ?> But calls in either the header.php or footer.php to methods in my class fail with "Call to a member function is not an object". I understand what the error means but I don't understand why. I thought all functions and classes defined in an include file have global scope. As per PHP.NET's documentation: "When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope." The include that creates the class is something that I have inherited from another developer and I actually can't change the scope. I've tried with global $site = new WebSite($site_name);. It actually breaks the entire site. How can I access classes, properties, methods in an include file? Any help would be appreciated. I've been racking my head for several days now on it and it's probably some newbie thing that I am completely overlooking. I hope I've provided enough background and info. Thanks, Brian I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help... So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me i have created an object in one page. it has a submit button which upon clicking opens a new page. is it possible to access that created object and its data members in that second page? here is the code for creating the object in the first page. $viewcart = new Cart(); $viewcart->GetProductCart($user); I am calling an object from another class in the constructor of first class but when I call it in another function it does not access it's object. Here is the code. Code: [Select] <?php /* This is controller.php used to control the flow of data between view.php and model.php. This file cotains all the controlling mechanism of the data It was created on 11th Feb 2011 By Narjis Fatima for an Open Source Project and contains all the includes to the database etc. */ include ("view.php"); include ("functions.php"); $name = stripslashes($_GET['username']); $email = stripslashes($_GET['email']); //echo "in controller.php"; check_validate_input($name, $email); $newUser = new controller($name, $email); $action=$_GET['t']; $newUser->display_view($action); class controller { public $my_model; //is an object of model class public $user_info;//=array('id' , 'username' ,'role','email','interests','location', 'homepage'); function __construct($name,$email) { $my_model = new model(); $user_info = $my_model->check_members($name,$email); echo "<pre>"; print_r ($user_info); } function __destruct() { } function display_view($token) { echo "In display function"; echo "<pre>"; print_r ($user_info); if ($this->user_info == NULL) { if (($token=="register")) { show_registration_form(); } else{ show_mailing_form(); } } if ($this->user_info['role'] == "admin") { $myView = new view(); $myView->view_admin_menu(); } if ($this->user_info['role'] == "user") { $myView = new view(); $myView->view_user_menu() ; } }//close of function display_view() } /* name and email cominfg from index.php would be checked by the controoler class to be checked if it a vaild name and email. The database would be connected n the model.php*/ ?> The code for model.php is as follows Code: [Select] <?php //This is model.php created on 10th Feb 2011 .It deals with daytabase connection // //By NArjis Fatima //For the project of EDUForge an Open Source Software //include ("register.php"); class model{ public $dbh; public $user_arr=array('username','password','email','location','interest','homepage'); //cunstructor of model class //function to connect to database function __construct(){ try{ $this->dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } } public function check_members($username,$email) { //get_connected(); $sql = "SELECT * FROM account WHERE (username='" .$username ."' AND email='" .$email."')"; $sth = $this->dbh->prepare($sql); $sth->execute(); $result = $sth->fetch(); /* echo('<pre>'); print_r($result);*/ return ($result); } public function insert_data($user_info) { //$user_info = $user_in; //$dbh; try{ $dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } $dbh->exec("INSERT INTO account (username, userpassword, email, role, location, interest, homepage) VALUES ('" .$user_info['username']."','".$user_info['password'] ."','".$user_info['email']."', 'user','".$user_info['location']."','".$user_info['interests'] ."','".$user_info['homepage']."')"); } } ?> Please somebody help me. I am really stuck. I am also sending my attachment. Hi guys, I have below values in array Code: [Select] stdClass Object ( [Category] => stdClass Object ( [ChildCategoryDescription] => 50s / 60s ERA [ChildCategoryID] => 87 [GrandchildCategoryDescription] => - [GrandchildCategoryID] => 25 [ParentCategoryDescription] => CONCERTS [ParentCategoryID] => 2 ) [Description] => Tony Bennett [ID] => 1073 [HomeVenueID] => 0 ) When am calling Desciption object by $resultsObj->Description then i got the result " Tony Bennett" but i do not know to get the value GrandchildCategoryID . Just i tried this Code: [Select] echo $resultsObj->$resultsObj->ParentCategoryID and i got below error. Catchable fatal error: Object of class stdClass could not be converted to string in D:\Program Files\xampp\htdocs\t1\genericLib.php on line 255. How i can get this value... Folks, I need to Extract the Content of "[content] => " Class from the output of the below Script: <?php $keywords = file_get_contents('http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q="paintball"'); $keywords = json_decode($keywords); print_r($keywords); ?> Output is like: Quote stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball.com/ [url] => http://www.paintball.com/ [visibleUrl] => www.paintball.com [cacheUrl] => http://www.google.com/search?q=cache:Zcnr-K8jU4YJ:www.paintball.com [title] => PaintBall.com [titleNoFormatting] => PaintBall.com [content] => Information and meeting place for new and experienced players. Features industry news, equipment reviews, information for new players, links to online ... ) [1] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.zephyrpaintball.com/ [url] => http://www.zephyrpaintball.com/ [visibleUrl] => www.zephyrpaintball.com [cacheUrl] => http://www.google.com/search?q=cache:EkBfV3VsT9UJ:www.zephyrpaintball.com [title] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [titleNoFormatting] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... ) [2] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.addictinggames.com/paintballthegame.html [url] => http://www.addictinggames.com/paintballthegame.html [visibleUrl] => www.addictinggames.com [cacheUrl] => http://www.google.com/search?q=cache:TM1GFy3lDIQJ:www.addictinggames.com [title] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [titleNoFormatting] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) [3] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball-online.com/ [url] => http://www.paintball-online.com/ [visibleUrl] => www.paintball-online.com [cacheUrl] => http://www.google.com/search?q=cache:rm9AvRxLLX4J:www.paintball-online.com [title] => Paintball Guns & Markers at Paintball-Online.com [titleNoFormatting] => Paintball Guns & Markers at Paintball-Online.com [content] => The Internet's largest paintball store featuring over 4000 paintball guns, markers and other gear. Free shipping and 10% off for all VIP members. ) [4] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://en.wikipedia.org/wiki/Paintball [url] => http://en.wikipedia.org/wiki/Paintball [visibleUrl] => en.wikipedia.org [cacheUrl] => http://www.google.com/search?q=cache:h3rpb57aWfcJ:en.wikipedia.org [title] => Paintball - Wikipedia, the free encyclopedia [titleNoFormatting] => Paintball - Wikipedia, the free encyclopedia [content] => Paintball is a sport in which players compete, in teams or individually, to eliminate opponents by hitting them with capsules containing food coloring and ... ) [5] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.ansgear.com/ [url] => http://www.ansgear.com/ [visibleUrl] => www.ansgear.com [cacheUrl] => http://www.google.com/search?q=cache:uiYno-g6MOkJ:www.ansgear.com [title] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [titleNoFormatting] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [content] => Ansgear has Paintball guns and Paintball equipment for everyone. Get your Paintball equipment for cheap. All Paintball gear on sale! ) [6] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.pbreview.com/ [url] => http://www.pbreview.com/ [visibleUrl] => www.pbreview.com [cacheUrl] => http://www.google.com/search?q=cache:OzXP0G1QzFMJ:www.pbreview.com [title] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [titleNoFormatting] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [content] => All things paintball on pbreview.com. Paintball gun & equipment reviews, paintball videos, a paintball field locator for paintball games & tournaments. ) [7] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => Desired Output: Quote [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) .......................... Till the End of the Page... How can it be achieved? Cheers Natasha T why is this not working? <?php class registration{ public $email = $_POST["email"]; public $username = $_POST["username"]; public $password = $_POST["password"]; //var $username = $_POST["confirmPassword"]; function validateFields(){ echo $this->$email; echo $this->$username; echo $this->$password; //echo $this->$confirmPassword; } } registration->validateFields(); ?> Im getting error: Parse error: syntax error, unexpected T_VARIABLE on the first property declaration $email. Hi all
i am using the code below, but am getting the error
Object of class mysqli_result could not be converted to int
<?php $sql="SELECT lng,lng_prefix FROM tbl_languages where active = 1"; $result=mysqli_query($dbConn, $sql)or die(mysqli_error($dbConn)); //problem line if(mysqli_num_rows($result==1)){ ?>The code continues with what I want to happen based on the result. What does the error mean and how do I fix it? I'm receiving the error "Object of class player could not be converted to string" yet I cannot find why what I'm inputting is an object and not a string. As far as I can see it is a string and this error shouldn't be happening, yet it is... A form submits to a page which gets the data thus: Code: [Select] <?php case "updplayer": if(!isset($_GET['id']) || !isset($_POST['kit']) || !isset($_POST['level']) || !isset($_POST['group']) || !isset($_POST['state'])) { header("location:admin.php?mode=settings&error=info&sid=$user->sid"); exit; } $var = "player" . $_GET['id']; $$var->kit = mysql_real_escape_string($_POST['kit']); $$var->level = mysql_real_escape_string($_POST['level']); $$var->group = mysql_real_escape_string($_POST['group']); $$var->state = mysql_real_escape_string($_POST['state']); $$var->update(); header("location:admin.php?sid=$user->sid"); exit; break; The update function is: Code: [Select] <?php function update() { echo "Name: $this->name <br /> Kit: $this->kit <br /> Level: $this->level <br /> Group: $this->group <br /> State: $this->state <br />"; $sql = "UPDATE `players` SET `name` = '" . $this->name . "', `preferredKit` = '" . $this-kit . "', `gamingLevel` = '" . $this->level . "', `group` = '" . $this->group . "', `draftState` = " . $this->state; if(!mysql_query($sql)) { return mysql_error(); } return TRUE; } I added the echo's in for error checking. They output exactly what was expected. What is wrong with this? Error occurs on the "$sql = " line. 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 don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help thanks I can not understand why this isn't working, basically it works in one place but not the other I have this in my main class: class phpLive{ public function loadCore(){ foreach(glob($this->location."/core/*/*.core.php") as $coreFile){ $info = (object)pathinfo($coreFile); require_once $coreFile; $pos = strrpos($info->dirname, "/"); $coreMedia = substr($info->dirname, $pos + 1); $className = str_replace(".core", "", $info->filename); $instance = strtolower($className); $this->$coreMedia->$instance = new $className(); } } } On the page that I run (index.php), I use this: $_live->example->loadurl(); which is in a class that looks like this: <?php class ExampleClass extends phpLive{ public function __construct(){ $this->loadCore(); } public function loadurl(){ $this->net->http->getHttp('http://google.com'); } } ?> and I get the following error: Quote Notice: Undefined property: ExampleClass::$net in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Notice: Trying to get property of non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Fatal error: Call to a member function getHttp() on a non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 but, when I run this on the main page: $_live->net->http->getHttp("http://google.com"); The code works just fine. Why doesn't the first one work (the above is the actual code, copy and pasted from my editor)? why do i keep getting this error from line 7? Object of class stdClass could not be converted to string Code: [Select] <?php include_once"../includes/db_connect.php"; $item_number="2"; $custom="54298"; $query=mysql_query("SELECT `prodID`, `quanity` FROM `cart` WHERE `sessID`='$custom'") or mysql_error(); while($cart=mysql_fetch_object($query)){ mysql_query("INSERT INTO `orderItems` ( `id` , `orderInfoID` , `productID` , `quanity` ) VALUES ('', '$item_number', '$cart-> prodID', '$cart->quanity');"); } mysql_query("UPDATE `cart` SET `show`='1' WHERE `sessID`='$custom'"); ?> The following is an extract of PHP code I have interacting with a MySQL database and I keep getting the "object of class mysqli_result could not be converted to string" error on the line of code inside my loop. This is my code.
#This is just storing a single integer, a moduleID
$sqlmodID = mysqli_query($con,"select moduleID from module_details WHERE moduleName = '$moduleName' AND lecturerID = '$lecturerID'"); #This is a query to get relevant idNumbers $sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";
#Running the previous statement $result = mysqli_query($con, $sqlstudent);
#Storing the statements results in an array $row = mysqli_fetch_array($result);
#I'm not sure if this line is necessary but it converts the array values into a string (I'm storing the ID's as strings as they contain numbers and letters) $studentArray = array_map('strval', $row);
#The error flashes on my condition of this loop. I'm trying to take each element of my array, and enter it to my table, assigning each variable the same ModuleID.
for($i=0; $i < count($studentArray); $i++){
Any help would be much appreciated. I hope I've explained my code sufficiently. |