PHP - Function Called On A Non-object
ERROR 0 Fatal error: Call to a member function execute() on a non-object ...
i've tested the $mysqli and $stmt, both are objects, i have other requests that work well and are built the same way (copy - paste) all vars on the query are also ok. There are working functions over and under this part of my code, if i remove it everything works fine. Code: [Select] $query2 = "INSERT INTO TABLE_NAME(accountSmtp, passwordSmtp, merchantID, adsPrice, adsWidth, adsHeigh, adsAmount, email, emailFrom, adsSense) VALUES('$gmailUser', '$gmailPassword', '$merchantID', '$prix', '$width', '$height', '$adsAmount', '$email', '$from', '$sense')"; if (!$stmt = $mysqli->prepare($query2)) { printf("Erreur : %d.\n", $stmt->errno); print_r($query2); } /* execute statement */ $stmt->execute(); //close statement $stmt->close(); Similar TutorialsHere's some of my code. The fault is when AJAX sends the dataString to sendpm.php, it should call the function. But nothing is happening. If i put the sendprivatemessage query in sendpm.php page, the data is sent to mysql. What is the solution, so i don't have to put the query on sendpm.php? jquery - some of it Code: [Select] $.ajax({ type: "POST", url: "/sendpm.php", data: dataString, success: function() { window.location.href = 'http://www.stackway.com/cp/messages=outbox'; } }); sendpm.php Code: [Select] include "database.php"; $to = $_POST['to']; $from = $_POST['from']; $subject = $_POST['subject']; $body = $_POST['body']; $database2 = new Database(); $database2->opendb(); $database2->sendprivatemessage($to,$from,$subject,$body); $database2->closedb(); sendprivatemessage function Code: [Select] function sendprivatemessage($to,$from,$subject,$body) { $insert = mysql_query("INSERT INTO privatemessage VALUES ('','$subject','$body','$to','$from','1',NOW(),'','','')",$this-connect); } I have 2 forms on a page, 1 with a selection of newly registered accounts and another that displays the information on the user. What I need to happen is when a user is selected from the first form, the second form is populated with the data. I'm trying to do this with a combination of php and javascript, however whenever a user is selected the function isn't being called at all as far as I can tell. Can anyone help me get this working please? Code: [Select] <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Fearless Bandits :: Admin Control Panel</title> </head> <body> <?php //Check for config file and initiate session. require("config.php"); session_start(); //Connect to DB if(!$con) die('Could not connect: ' . mysql_error()); mysql_select_db("$dbname") or die("Cannot select DB"); //Check user authorisation if(!isset($_COOKIE['user'])) { echo "Error: Cookies must be enabled. Please enable cookies in your browser and try again.<br>"; return; } else { $user=$_SESSION['user']; $sql="SELECT * FROM users WHERE username='$user' and access='2'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count == 0) { echo "Error: Unauthorised access detected."; return; } } include("header.php"); echo "Admin Control Panel<br>"; //Check for mode, if no mode set to 0 if(isset($_GET['mode'])) $mode=$_GET['mode']; else $mode=0; //Display information based on mode switch($mode){ //Check for new applications case 1: echo "<a href=\"admin.php?mode=0\">Back</a><br>"; $sql="SELECT * FROM users WHERE newreg='1'"; $result=mysql_query($sql); $count=mysql_num_rows($result); $newuser = NULL; $newuid = NULL; $newapi = NULL; $newmember = 0; //If there is more than one load results into an array if($count > 0) { echo "There is at least 1 new user:<br>"; $i = 0; while($row=mysql_fetch_array($result)) { $newaccounts[$i] = $row['username']; $i++; } for($i=0; $i < $count; $i++) { echo "User " . $i . ": " . $newaccounts[$i] . "<br>"; } //Select user echo "<form name=\"selectuser\" action=\"\">"; echo "<select name=\"username\" onChange=\"newaccntsUpdate(this);\">"; echo "<option value=\"\" selected=\"selected\"></option>"; for($i=0; $i < $count; $i++) { echo "<option value=\"" . $newaccounts[$i] . "\">" . $newaccounts[$i] . "</option>"; } echo "</select><br>"; echo "</form>"; //Output array into form. echo "<form name=\"newaccnts\" method =\"post\" action=\"verify_admin.php?form=1\">"; echo "Username: <input name=\"newuser\" type=\"text\" id=\"newuser\" value=\"" . $_SESSION['newuser'] . "\">"; echo "UID: <input name=\"newuid\" type=\"text\" id=\"newuid\" value=\"" . $_SESSION['newuid'] . "\">"; echo "API: <input name=\"newapi\" type=\"text\" id=\"newapi\" value=\"" . $_SESSION['newapi'] . "\">"; if($newmember == 0) echo "Member: <input name=\"newmember\" type=\"checkbox\" id=\"newmember\" value=\"1\"><br>"; else echo "Member: <input name=\"newmember\" type=\"checkbox\" checked= \"checked\" id=\"newmember\" value=\"1\"><br>"; echo "<input name=\"submit\" type=\"submit\" value=\"Submit\">"; echo "</form>"; } break; //Select a mode default: echo "Please select a function below:<br>"; echo "<ul>"; echo "<li><a href=\"admin.php?mode=1\">Check for new applications</a></li>"; echo "<li><a href=\"admin.php?mode=2\">Modify an existing account</a></li>"; echo "<li><a href=\"admin.php?mode=3\">Reset a password</a></li>"; echo "<li><a href=\"admin.php?mode=4\">Delete an account</a></li>"; echo "<ul>"; break; } mysql_close($con); //Update newaccnts function. Pull user info from databse and then run javascript function newaccntsUpdate() { echo "newaccntsUpdate executed<br>"; //Error checking //Identify username $newuser=identifyUser(); //If username is NULL or blank return if($newuser == NULL || $newuser == "") return; $sql = ("SELECT * FROM users WHERE username='$newuser'"); $result = mysql_query($sql); $row = mysql_fetch_array($result); $_SESSION['newuser'] = $newuser; $_SESSION['newuid'] = $row['uid']; $_SESSION['newapi'] = $row['api']; $_SESSION['newmember'] = $row['member']; //Update form with details updateForm(); return; } ?> <script language = "Javascript"> //Identify which user has been selected function identifyUser() { $newuser = document.selectuser.username.value; alert('identifyUser executed'); //Error checking return($newuser); } //Update form function updateForm() { document.newaccnts.newuser.value = $newuser; document.newaccnts.newuid.value = $_SESSION['newuid']; document.newaccnts.newapi.value = $_SESSION['newapi']; alert('updateForm executed'); //Error checking return; } </script> </body> </html> I apologise if I've butchered the code, I'm still learning. Getting a bit desperate as I've tried a lot of things, so any help very appreicated! The concept im struggling with works like this: 1.) There are graphics of people on a page. There is a textbox to the right of the screen which outputs data that corresponds to the tutor. 2.) What i want is that when a user rolls his mouse over the picture, the data in the textbox immediately updates, which is done via php 3.) The issue is thus calling a php function within onmouseover="" from a javascript command. 4.) The function only changes the values that should be displayed (but doesnt work anyway) - is there a way to test whether a php function is being called correctly? And do i need to include some kind of page refresher? Thanks a lot for your help ****************************************** The code as I have it currently is this. ... Code: [Select] // Default setting to display a random persons data at page startup <? $username="removedforprivacy"; $password="removedforprivacy"; $database="tutors"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM tutors"; $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); $i=rand(0,5); $id=mysql_result($result,$i,"id"); $name=mysql_result($result,$i,"name"); $degree=mysql_result($result,$i,"degree"); $ib=mysql_result($result,$i,"ib"); $subjects=mysql_result($result,$i,"subjects"); $experience=mysql_result($result,$i,"experience"); $style=mysql_result($result,$i,"style"); $pic=mysql_result($result,$i,"pic"); ?> //This bit outputs all the graphics. Only the first immage calls the php updater function. $whichpic defines the flag for the person, which is passed to the updater function. </p> <p class="bodytext"><a href="" onclick="" onmouseout="MM_swapImgRestore()" onmouseover="<? php updater($whichpic=1); ?>"><img src="../Tutors/Photos/tim2.gif" name="Image15" width="100" height="100" border="0" id="Image15" /></a><a href="max.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image16','','../Tutors/Photos/max1.gif',1)"><img src="../Tutors/Photos/max2.gif" alt="max" name="Image16" width="100" height="100" border="0" id="Image16" /></a><a href="nico.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image17','','../Tutors/Photos/nico1.gif',1)"><img src="../Tutors/Photos/nico2.gif" alt="nico" name="Image17" width="100" height="100" border="0" id="Image17" /></a><a href="sasha.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image18','','../Tutors/Photos/sasha1.gif',1)"><img src="../Tutors/Photos/sasha2.gif" alt="sasha" name="Image18" width="100" height="100" border="0" id="Image18" /></a> </p> //Where the php data is output <p class="sideheader">FEATURED TUTOR</p> <p><img src="<? echo " $pic"; ?>" width="200" height="200"></p> <p><strong>Name: </strong> <? echo "$name"; ?></p> <p><strong>Degree: </strong> <? echo "$degree"; ?></p> <p><strong>IB: </strong> <? echo "$ib"; ?></p> <p><strong>Subjects Taught: </strong> <? echo "$subjects"; ?></p> <p><strong>Teaching Experience: </strong> <br /> <? echo "$experience"; ?> </p> <p><strong>Teaching Style:<br /> </strong><? echo "$style"; ?> .</strong> </p> <p><!-- end .sidebar2 --></p> </div> // The updater function to call, which changes the information displayed <? php function updater($whichpic) { $i = $whichpic; $id=mysql_result($result,$i,"id"); $name=mysql_result($result,$i,"name"); $degree=mysql_result($result,$i,"degree"); $ib=mysql_result($result,$i,"ib"); $subjects=mysql_result($result,$i,"subjects"); $experience=mysql_result($result,$i,"experience"); $style=mysql_result($result,$i,"style"); $pic=mysql_result($result,$i,"pic"); } ?> This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=346692.0 function chk_error($site_mode, $obj) { if( $site_mode == 'dev' ) { echo'Error : ('. $obj->errno .') '. $obj->error; } } chk_error($site_mode, $stmt);the above is not working for me. it echos out the text but no values for errno and error. what am i doing wrong? Ok, so I don't really understand a lot about OOP. I was given a two big files full of classes and functions. We were hand coding this file for each use. My objective was to make an array we could use to ease the pain of coding these features. Here is an example of what is happening to me. Can someone advise me conceptually on what to do. Code: [Select] include('Tons of files included here'); $myarray = array( 0 => array("question" => "answer"), 1 => array("question1" => "answer1") ); class BigClass { var $a var $b function fiststep(){ global $myarray; foreach($myarray as $anarray) { $this->$anarray = new includedfunction1($anarray["question"]); $this->$anarray->Values = array(array("yes", "yes"), array("no", "no")); $this->$anarray->Multiple = true; } } function nthstep(){ global $myarray; foreach($myarray as $anarray) { $this->$anarray->astep(); // Error occurs: Call to a member function on a non-object } } } include('Tons of files included here'); There seem to be a number of steps that occur in one of the 10-20 include files before the data comes back to the nthstep. Once it comes back. I cannot seem to get it to be recognized as an object. If I were to manually type out the contents of $anarray. I get NO error. I am very over my head. Does anyone have a conceptual idea of my issue? Hi Guys
I wonder if someone can explain something that is probably quite basic.
When I try to add an event listener and target a normal function this works fine - e.g. 'window.addEventListener('load',test)'. However, if I try to target a function that is a property of an object this fails - e.g. 'window.addEventListener('load',initialiser.init)'. Further in this latter case I also get a console log saying it's undefined.
The code for this example is below.
So my question is why does it fail onload when I use a function in an object as opposed to a straight function? Presumably it's something to do with the way the document and the code are loaded or initialised but what is it that makes them behave differently.
Thanks,
Drongo
<script> //this function call works fine //window.addEventListener('load',test); //this functiton call fails and is undefined in console window.addEventListener('load',initialiser.init); //example object holding a method var initialiser = { init:function(){ alert('Init called!'); } }; //some random function function test(){ alert('test called!'); } </script> Edited by Drongo_III, 18 May 2014 - 10:59 AM. I am getting this error while building OOP portal.
Fatal error: Call to a member function count() on a non-object in C:\Users\Rishi\Documents\xampp\htdocs\PDO\Pitch_It\index.php on line 6
My index.php file:
<?php Hi, I have the following class: class User { private $_db; public function __construct($user = null) { $this->_db = DB::getInstance(); ....... } public function find($user = null) { if($user) { $field = (is_numeric($user)) ? 'id' : 'username'; $data = $this->_db->get('users', array($field, '=', $user)); if($data->count()) { ......... return true; } } return false; }In class DB I have: public static function getInstance() { if(!(self::$_instance)): self::$_instance = new self(); endif; return self::$_instance; }public function get() in class DB, after processing, returns $this, the single instance of class DB, this is assigned to $data which is then used to invoke public function count(), a member function of class DB. I am getting the following error: Fatal error: Call to a member function count() on a non-object. I would be very grateful if someone can point out my mistake. what's wrong in this line $tpl->set('main_content',set_block($heading,'center',$err_tpl->fetch(load_template('error.tpl')))); Hi I did something in phpmyadmin the other day and I cant my site back to work. please see the attatched pdf with print screens of what I did. Basically I was trying to add this: Code: [Select] INSERT INTO `PP088_config_options` ( `id` , `category_name` , `name` , `value` , `config_handler_class` , `is_system` , `option_order` , `dev_comment` ) VALUES ( NULL , 'general', 'installation_base_language', 'se_se', 'StringConfigHandler', '0', '12', NULL ); in one of the tables. When visiting www.konto.gradeup.se you will see the error message. I inserted the code from the DB.class.php file that I think is causing the problem. Code: [Select] */ static function escape($value) { return self::connection()->escapeValue($value); } // escape /** * Escape field / table name line 262 is the line with that starts with return self::connection Thanks so much in advance. Im novice at phpmyadmin Code: [Select] <?php /** * This function holds open database connections and provides interface to them. It is also used * for SQL logging * * @version 1.0 * @http://www.projectpier.org/ */ final class DB { /** ID of primary connection **/ const PRIMARY_CONNECTION_ID = 'PRIMARY'; /** * Collection of connections * * @var array */ static private $connections = array(); /** * ID of primary connection. This connection will be used if connection name is not suplied * * @var string */ static private $primary_connection = self::PRIMARY_CONNECTION_ID; /** * SQL log * * @var array */ static private $sql_log = array(); /** * This function will return specific connection. If $connection_name is NULL primary connection will be used * * @access public * @param string $connection_name Connection name, if NULL primary connection will be used * @return AbstractDBAdapter */ static function connection($connection_name = null) { if (is_null($connection_name)) { $connection_name = self::getPrimaryConnection(); } // if return array_var(self::$connections, $connection_name); } // connection /** * Create new database connection * * @access public * @param string $adapter Adapter name (currently only mysql adapter is implemeted) * @param array $params Connection params * @param string $connection_name Name of the connection, if NULL default connection ID will be used * @return boolean * @throws FileDnxError * @throws DBAdapterDnx */ static function connect($adapter, $params, $connection_name = null) { $connection_name = is_null($connection_name) || trim($connection_name) == '' ? self::PRIMARY_CONNECTION_ID : trim($connection_name); $adapter = self::connectAdapter($adapter, $params); if (($adapter instanceof AbstractDBAdapter) && $adapter->isConnected()) { self::$connections[$connection_name] = $adapter; return $adapter; } else { return null; } // if } // connect /** * This function will include adapter and try to connect. In case of error DBConnectError will be thrown * * @access public * @param string $adapter_name * @param array $params * @return AbstractDBAdapter * @throws DBAdapterDnx * @throws DBConnectError */ private function connectAdapter($adapter_name, $params) { self::useAdapter($adapter_name); $adapter_class = self::getAdapterClass($adapter_name); if (!class_exists($adapter_class)) { throw new DBAdapterDnx($adapter_name, $adapter_class); } // if return new $adapter_class($params); } // connectAdapter /** * Figure out adapter location and include it * * @access public * @param string $adapter_class * @return void */ private function useAdapter($adapter_name) { $adapter_class = self::getAdapterClass($adapter_name); $path = dirname(__FILE__) . "/adapters/$adapter_class.class.php"; if (!is_readable($path)) { throw new FileDnxError($path); } // if include_once $path; } // useAdapter /** * Return class based on adapter name * * @access public * @param string $adapter_name * @return string */ private function getAdapterClass($adapter_name) { return Inflector::camelize($adapter_name) . 'DBAdapter'; } // getAdapterClass // --------------------------------------------------- // Interface to primary adapter // --------------------------------------------------- /** * Try to execute query, ignore the result * * @access public * @param string $sql * @return true */ static function attempt($sql) { $arguments = func_get_args(); array_shift($arguments); $arguments = count($arguments) ? array_flat($arguments) : null; try { self::connection()->execute($sql, $arguments); } catch(Exception $e) { } return true; } // execute /** * Execute query and return result * * @access public * @param string $sql * @return DBResult * @throws DBQueryError */ static function execute($sql) { $arguments = func_get_args(); array_shift($arguments); $arguments = count($arguments) ? array_flat($arguments) : null; return self::connection()->execute($sql, $arguments); } // execute /** * Execute query and return first row from result * * @access public * @param string $sql * @return array * @throws DBQueryError */ static function executeOne($sql) { $arguments = func_get_args(); array_shift($arguments); $arguments = count($arguments) ? array_flat($arguments) : null; return self::connection()->executeOne($sql, $arguments); } // executeOne /** * Execute query and return all rows * * @access public * @param string $sql * @return array * @throws DBQueryError */ static function executeAll($sql) { $arguments = func_get_args(); array_shift($arguments); $arguments = count($arguments) ? array_flat($arguments) : null; return self::connection()->executeAll($sql, $arguments); } // executeAll /** * Start transaction * * @access public * @param void * @return boolean * @throws DBQueryError */ static function beginWork() { return self::connection()->beginWork(); } // beginWork /** * Commit transaction * * @access public * @param void * @return boolean * @throws DBQueryError */ static function commit() { return self::connection()->commit(); } // commit /** * Rollback transaction * * @access public * @param void * @return boolean * @throws DBQueryError */ static function rollback() { return self::connection()->rollback(); } // rollback /** * Return insert ID * * @access public * @param void * @return integer */ static function lastInsertId() { return self::connection()->lastInsertId(); } // lastInsertId /** * Return number of affected rows * * @access public * @param void * @return integer */ static function affectedRows() { return self::connection()->affectedRows(); } // affectedRows /** * Escape value * * @access public * @param mixed $value * @return string */ static function escape($value) { return self::connection()->escapeValue($value); } // escape /** * Escape field / table name * * @access public * @param string $field * @return string */ static function escapeField($field) { return self::connection()->escapeField($field); } // escapeField /** * Prepare string. Replace every '?' with matching escaped value * * @param string $sql * @param array $arguments Array of arguments * @return string */ static function prepareString($sql, $arguments = null) { if (is_array($arguments) && count($arguments)) { foreach ($arguments as $argument) { $sql = str_replace_first('?', DB::escape($argument), $sql); } // foreach } // if return $sql; } // prepareString // --------------------------------------------------- // Getters and setters // --------------------------------------------------- /** * Get primary_connection * * @access public * @param null * @return string */ static function getPrimaryConnection() { return self::$primary_connection; } // getPrimaryConnection /** * Set primary_connection value * * @access public * @param string $value * @return null * @throws Error if connection does not exists */ static function setPrimaryConnection($value) { if (!isset(self::$connections[$value])) { throw new Error("Connection '$value' does not exists"); } // if self::$primary_connection = $value; } // setPrimaryConnection /** * Add query to SQL log * * @access public * @param string $sql * @return void */ function addToSQLLog($sql) { self::$sql_log[] = $sql; } // addToSQLLog /** * Return SQL log * * @access public * @param void * @return array */ function getSQLLog() { return self::$sql_log; } // getSQLLog } // DB ?> Hi All, My appologies in advance. I am pretty sure that this has probably been answered before by someone...but for the life of me I carn't find the answer in any forums. My basic question is this. Can you create an object at the beginning of a script, and then call its methods from within functions? I have coded the following: <?php ///import classes to use require "booking_form_gui.php"; $booking = new booking_form_gui(); function _booking_form($form_state){ ///$booking = new booking_form_gui(); return $booking -> date_selection(); <----------this line causes the error I guess } The problem is that when I run this code, I get an error message similar to the following: Fatal error: Call to a member function date_selection() on a non-object in /var/www/drupal_6/sites/default/modules/booking_system/booking_form/booking_form.module on line 127 Anyone any ideas how I could get round this? Thanks, Mark. i am really struggling and i have no idea what to do. Call to a member function stmt_init() on a non-object on this code. if (isset($_POST['insert'])) { require_once('includes/connection.php'); // initialize flag $OK = false; // create database connection $conn = dbConnect('write'); // initialize prepared statement $stmt = $conn->stmt_init(); // create SQL i am using a book but i have tried it many ways and the same error occurs. i have looked on forums and they say that i have not set up the users correctley. but for a test i give my user all the permitions that i could and same problem. the error occurs on this line $stmt = $conn->stmt_init(); with the error message stating Call to a member function stmt_init() on a non-object please if you have seen this before could you help thanks in advance I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object? class shoutbox { private $db; function __construct($dbname, $username, $password, $host = "localhost" ) { # db conections try { $this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password); } catch(PDOException $e) { echo $e->getMessage(); } } function getShouts() { $sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0'); return $sql_shouts->fetch(PDO::FETCH_OBJ); } } Random Error that im getting on my webhost, not localhost. Fatal error: Call to a member function fetch_assoc() on a non-object in /home/*****/index.php on line 127 Line 127: while ($premium = $row->fetch_assoc()) { Code: <div class="toplist-content"> <table cellspacing="0"> <tbody> <?php $row = $home->getList(1); while ($premium = $row->fetch_assoc()) { ?> <tr class="table"> <td class="name"><a href="server.html"> <h3> <?php echo ucfirst($premium['servername']); ?> </a> <font size='1.5'><?php echo ucfirst(substr($premium['serverdesc'],0,25)). "..."; ?> </h3> </font> </td> <td class="revision"><h3> <?php echo ucFirst($premium['revision']); ?> </h3></td> <td class="votes"><h3> <?php echo $premium['vote']; ?> </h3></td> <td class="status"><?php if($home->getStatus($premium['host'], $premium['port']) == true) { echo "<span class='ticket open'>Online</span>"; } else { echo "<span class='ticket closed'>Offline</span>"; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> The getList() function : function getList($premium) { $query = $this->con->query("SELECT * FROM `".$this->prefix."servers` WHERE `premium` = '".$premium."' && `ban` = '0' ORDER BY (SELECT COUNT(*) FROM `".$this->prefix."votes` WHERE `serverId` = '".$this->prefix."servers.id') DESC") or die(mysqli_error()); return $query; } I have a database called "mp_users" with the following setup: Code: [Select] CREATE TABLE IF NOT EXISTS `mp_users` ( `id` int(10) unsigned default NULL auto_increment, `uid` int(10) unsigned NOT NULL, `username` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `points` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; When I try to run the following query, I get an error: Quote SELECT COUNT(id) AS user_exists FROM `mp_users` WHERE uid=$uid LIMIT 1; Error: Fatal error: Call to a member function query() on a non-object in /home/user/public_html/marketplace-functions.php on line 52 Here is the code: Code: [Select] <?php require_once "config.php"; $sql = new mysqli($db1['host'], $db1['user'], $db1['pass'], $db1['db']); function checkUserExists($uid){ // Query $q = "SELECT COUNT(id) AS user_exists FROM `mp_users` WHERE uid=$uid LIMIT 1;"; echo $q; $q = $sql->query($q); $r = $q->fetch_assoc(); // Any results? if($r['user_exists'] == 0){ // redirect to runonce... header('Location: marketplace.php?do=runonce&return='.urlencode($_SERVER['QUERY_STRING'])); exit(); } } ?> Line 52 is the $q query. I really cannot see what the problem is. The database exists, I've tried it in phpMyAdmin and it runs without trouble, but this wont! Can anyone help? Thanks in advance i am tring to extend from DataAccess to Module... but is showing an error: location: Library/database.php <?php Class DatabaseAccess { public $db; public $sqlQuery; public function ConnectDB($host,$user,$password,$database){ $this->db = mysqli_connect($host,"",$password); if (mysqli_connect_errno()) { echo '<p>Cannot connect to DB: ' . mysqli_connect_error() . '</p>'; } $this->db &= mysqli_select_db($this->db,$database); } public function SqlQuery($sql) { return mysqli_query($this->db,$sql);//or die("Error:".mysqli_error()."<br />The Query:<b>$sql</b>"); } } ?> The Module class Location:Library/module.php <?php Class Module extends DatabaseAccess { public function DoInsert($tableName,$fields = array(),$values = array())//delete from table { $fields = implode(",", $fields); $values = implode("','", $values); return $this->db->SqlQuery ("INSERT INTO $tableName($fields) VALUES('$values')");//The error is here!!!!!!!!!!!!!!!! } } ?> and the controller file name: newProfile.php this is the cdode include "config.php"; include "Library/database.php"; include "Library/module.php"; $db = new DatabaseAccess; $db->ConnectDB(MYSQL_HOST_NAME,MYSQL_USER_NAME,MYSQL_PASSWORD,MYSQL_DATABASE);//define in config.php $db->Module = New Module; $db->Module->DoInsert("twitter_profiles", array(profile_user_name,profile_password,user_id), array($_POST['userName'],$_POST['password'],$userID));//DoInsert(tableName,Fields,Values) echo sysMessage("NewProfile.txt"); the error: Fatal error: /home/omerbsh/blalalala.com/tra/Library/module.php on line 59 the error is in the modle class where the comment: "The error is here!!!!!!!!!!!!!!!!" its cant to fine SqlQuery object but why??? thanks Hi, i'm having a problem with some coding ive done not too sure why I am getting the following error message Fatal error: Call to a member function escapeValue() on a non-object /commonResources/php.lib/validateForm.class.php on line 82 At first I thought it was my database class object wasn't being created, but double checked and I have create a new object called $database of the database class. Any ideas?? Code: [Select] <?php require_once ("/home/innova11/public_html/commonResources/dbConnection/dbConnection.php"); class validateForm { public $email, $fName, $surname, $addressLine1, $townCity, $county, $postcode, $contactNum, $comments, $recaptchaVal; public $resp; public $error; function validateRecaptcha2($recaptchaVal) { $this->recaptchaVal = $recaptchaVal; if(empty($this->recaptchaVal)) { return false; } else { $safe = $database->escapeValue($this->recaptchaVal); $sql = " SELECT * FROM test WHERE test = '".$safe."' "; $results = $database->sqlQuery($sql); if(mysql_num_rows($results)>0) { return true; } else { return false; } } } ?> When I use another class inside one class, I get this error Quote Call to a member function _safestring() on a non-object The code is here Code: [Select] <?php require ('db.inc.php'); $db = new db(); class common { function _cookiecheck() { if(!isset($_SESSION['username'])) { if(isset($_COOKIE['username'])&&isset($_COOKIE['password'])) { $pass = $db->_safestring($_COOKIE['password']); $user = $db->_safestring($_COOKIE['username']); $check = _query("select password from users where username='{$user}'"); if($check) { $_SESSION['username'] = $user; } } } } } ?> I get the error on the line when I call $db->_safestring(); Thanks for the help I am changing my script from connecting to the database within every function, to using one connection (in the main class). However, I am getting an error: Call to a member function query() on a non-object Here is the main class: <?php class main{ // the configuration vars public $config; // the current user variables public $uid = 0; // contains the user ID public $gid = 0; // contains the group ID // database variables public $DB; // contains the connection public $query_id; // contains the query ID public $query_count; // how many queries have there been? // cache variables public $cache; public $test = 'hi'; // initiate public function __construct(){ } // start up functions public function startup(){ // first, set up the caching if($this->config['use_memcache'] == true){ // start up cache require_once('cache.class.php'); $this->cache = new cache_TS(); } // now, set up the DB $this->connectToDatabase(); // now, set up the user session $this->setUserSession(); // are we logged in? If so, update our location if($this->uid > 0){ // update location $this->updateUserSession(); } } // connect to database public function connectToDatabase(){ // connect to database $this->DB = new mysqli($this->config['host'],$this->config['user'],$this->config['pass'],$this->config['db']); // were we able to connect? if(!isset($this->DB)){ // this is an error exit('could not connect to the database.'); } // test query $q = "SELECT id,title FROM topics WHERE id='1' LIMIT 1;"; $q = $this->DB->query($q); $r = $q->fetch_assoc(); echo $r['id'] . $r['title']; // send back return $this->DB; } // some removed.... The test query works fine. It fails he <?php class forum extends main{ public function viewTopic($tid){ // Connect To Database //$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']); // Get assorted details (topic, forum, etc) // Get topic details $tid = intval($tid); $tq = "SELECT * FROM `topics` WHERE id='$tid' LIMIT 1"; $tq = $this->DB->query($tq); $tr = $tq->fetch_assoc(); startup in main has already been called before forum is. The DB connects without failure. Can anyone see what the problem is? How can I get $this->DB->query to work? (The query works fine when it's ran in the main class) |