Reason for: Trying to get property of non-object in php - php

$EODQuery = "SELECT * FROM EOD WHERE Symbol LIKE '$start' LIMIT 1 OFFSET $limit";
$EODRes = $mysqli->query($EODQuery);
I get an error, but not when i directly query the database.
<?php $i = 0; while($i <= 4) { $EODRow = getEOD("A%",$i); $i++; echo $EODRow; } ?>

Your error message has nothing to do with the query itself. What's happening is this: You're calling a method query() on the $mysqli object - however, PHP thinks that it's not actually an object.
The reason for this can be:
You forgot to create this object (See http://www.php.net/manual/en/mysqli.connect.php). Here's an example:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
You mistyped the variable name, so your mysqli object is actually called something else.
The code you show is within a function or a method, but your $mysqli object is in the global scope. In this case, you should "load" it into the function scope, like this:
function doStuff() {
global $mysqli;
$mysqli->query(...);
}
For more information regarding variable scope, see this link: http://php.net/manual/en/language.variables.scope.php

On the first look it seems like you have forgotten to instantiate $mysqli, that leads to $mysqli not being an object, so you cant execute the query() method.

Related

query mysql database from inside a class using properties

Hi this is kind of an upgraded version of this question:
query mysql database from inside a class
The difference from the previous question, is i need a dynamic query not a static one or l$query = "SELECT col_1 FROM db.table"; So in order to have a dynamic query i need to use properties (or variables) so i can call different tables from that same class, or something like this "SELECT ‘$data’ FROM ‘$table’ ";
So far my class looks like this, similar to the previous question:
$mysqli = new mysqli("localhost", "root", "", "intranetpugle");
class crudmum {
private $table;
private $data;
private $mysqli;
function __construct($mysqli) {
$this->mysqli = $mysqli;
}
function runQuery($data2, $table2)
{
$this->table = $table2; $this->data = $data2;
$query = "SELECT '$this->data' FROM '$this->table' ";
$stmt = $this->mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($r);
while($stmt->fetch())
{
echo "<option>" . $r . "</option>";
}
}
};
This is how i run it:
$showme = new crudmum($mysqli);
$showme->runQuery("priority", "trackboards" );
Note: When i dont use variables or properties inside the query or somethng like this, SELECT priority FROM trackboards, the query does work, only when i input the properties or variables (like the given example) it does not work.
I get this error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\devserv\i+d\bootstrap\functions.php on line 76
Anyone see what am i doing wrong, of course there is a mistake with the database query any ideas on how to query the database right in a dynamic way within a class, sorry new with OOP with PHP!
found the mistake which was to add 'quotes' on the variables, like shown below:
$query = "SELECT '$this->data' FROM '$this->table' ";
The correct way would be to take out those 'quotes' on the variables or like this:
$query = "SELECT $this->data FROM $this->table ";
With that fix, the query runs just fine, guess i lacked attention to detail, thanx everyone for their help.

Error in my PDO function

I'm new to PDO CLASS programming, here's my question, I have this class that retrive some infos from DB and I really need something like that, I get the error on title:
Call to a member function prepare() on a non-object on query line:
$stmt = $this->db->prepare()
What I'm doing wrong?
class map{
private $db;
public $dir;
public $query;
function mapWant($query,$db,$dir){
$stmt = $this->db->prepare("SELECT ".$this->query." WHERE ID = :dir");
$stmt->execute(array(':dir'=>$this->dir));
$row=$stmt->fetch(PDO::FETCH_LAZY);
echo $row[0]; //I want retrive the only field that the result has
}
}
$map = new map();
$map->mapWant($dir,$db,"Breve");
$dir is a $_GET method that retrive only a number
$db = is PDO connection (that's work);
thank you in advance.
You are passing the $db reference as a parameter, but then trying to access it within the scope of your class. The same goes for $query and $dir.
You seem to be under the impression that any parameters passed to a method will be applied as class properties. This is not the case.
The following line:
$stmt = $this->db->prepare("SELECT ".$this->query." WHERE ID = :dir");
Should simply be:
$stmt = $db->prepare("SELECT ".$query." WHERE ID = :dir");
Provided that $db passed to $map->mapWant() is a valid database resource.

PDO object not in scope of a function

OK, I see some similar questions to mine, but their examples all use PHP classes...mine does not. Maybe that's the problem? I shouldn't need classes because my site is exceedingly simple at this point in time.
Anyway, I'm trying to use PDO to connect to a MySQL db. I connect to the db fine in a file called config.php, and include this file in index.php with require_once().
I can successfully query the db from another file called process.php, but the problem is within a function within that file; it seems my DBO object is out of scope within that function.
Here are the relevant code snippets:
index.php
require_once('./lib/config.php');
config.php
// tested and connects fine
$pdo = new PDO('mysql:host=' . $hostname . ';dbname=' . $dbname, $username, $password, array(
PDO::ATTR_PERSISTENT => true
));
process.php
<?php
...
// can call $pdo fine in this file outside of functions
...
function authenticate($u, $p) {
// can't call $pdo in here, error says $pdo is non-object
$que = $pdo->query('select user_id, user_pass from users where user_name = \'' . $u . '\' limit 1');
...
}
?>
By the way, I'm using PDO because I was having similar trouble with mysqli, and am trying to get away from mysql, which is apparently depreciated and discouraged.
EDIT: I should have clarified first based on the number of responses I got on this matter: I did try to pass $pdo in as a param to the function, with no luck or change in the error message.
SOLUTION: OK, apparently the problem was that I needed to add require_once('config.php') in my process.php file as well. Not sure why (wouldn't it already be included when index.php was run first?). Then I was able to successfully pass $pdo in as a param to my function, and voila.
That's pretty basic PHP stuff. Variables inside functions are local variables unless you use the global keyword to load them. I suppose you want this:
function authenticate(PDO $pdo, $u, $p) {
$que = $pdo->query('select user_id, user_pass from users where user_name = \'' . $u . '\' limit 1');
//...
}
Edit: If PHP claims that $pdo is not an object, it's not an object, so it doesn't really matter how it's passed to the function. Inspect the variable right before you call authenticate():
var_dump($pdo);
Without the relevant code there's no way to say why. (Assuming it's true that new PDO succeeds.)
You need to pass the PDO object as a parameter to the authenticate() function:
function authenticate(PDO $pdo, $u, $p) {
// ..as in the question..
}
Oh and you should be using a place holder for that username in the query, not string concatenation which is prone to SQL injection attacks.
because $pdo has been declared outside of the function authenticate it isn't available inside it. You need to either pass $pdo in
function authenticate($u, $p, $pdo) {
$que = $pdo->query('...');
}
or declare it as global inside the function to be able to access it
function authenticate($u, $p) {
global $pdo;
$que = $pdo->query('...');
}

How to put mysql inside a php function?

I have problem about putting mysql into a function showMsg(). The mysql is working fine if it is not wrapped by function showMsg(), but when I wrap it with function showMsg(), it gives error message "Warning: mysql_query(): supplied argument is not a valid". How to put mysql inside a php function? Below is my codes :
<?php
function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
<div>
<?php showMsg(); ?>
</div>
?>
Never use global.
Pass $connection into your function as an argument.
Logic and representation should be separated.
Read about MVC: here or here.
Global variables are evil, never use it. If someone suggests it - ignore all their answers.
You probably need:
global $connection;
(Inside the function, that is.)
See Variable Scope
As everyone mentioned, the issue has to do with variable scoping. Instead of add global $connection; you could consider a more OOP approach and consider:
A: passing the $connection variable into the function.
B: placing related functions in a class and pass the DB connection into the Class constructor.
for example:
class YourClass {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$this->connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
}
I don't have enough rep to comment. But I also like OZ_'s answer :)
$connection variable has no value assigned. The following code should solve your problem (add it at the beginning of the function):
global $connection;
But you should be aware of the fact, that using globals is not a good idea and you may want to:
(preferably) pass $connection variable within the parameter of the function, or
move $connection declaration from outside the function just into the function (if it does not cause additional problems), or
redeclare $connection variable within the function (again: if it will not cause additional problems),
Because variables are local to functions. You need to add this inside your function:
global $connection;
Simply put, functions ignore outside variables due to variable scope. You must let the declare the variable as being from the outside by using global or you can send $connection through a parameter.

PDO not working within function

I am trying to make a function to pull a page's content from a MySQL table using a PDO Prepare statement. My code works just fine outside of the function I defined, but no matter what I do it will not work within the function - I receive the following error:
Fatal error: Call to a member function prepare() on a non-object in /home/tappess1/public_html/pages/stations.php on line 6
Here is my PHP:
function getPageContent($page) {
$st = $db->prepare("SELECT * FROM content WHERE title LIKE ?");
$st->execute(array($page));
$pageContent = $st->fetch();
$text = wordwrap($pageContent['content'], 100, "\n");
$tabs = 4;
$text = str_repeat(chr(9), $tabs) . str_replace(chr(10), chr(10) . str_repeat(chr(9), $tabs), $text);
echo $text;
}
and then
<?php getPageContent(Main);?>
I have even tried using a query instead of prepare statement, simply calling getPageContent() and I receive the same error.
Thanks!
You are trying to access the variable $db which is outside your function's scope.
Either re-initialize your database within the function $db = new PDO...., or - probably better and easier in your case - import the global variable:
function getPageContent($page) {
global $db;
Where and how to best store the global database object is subject of a lot of discussion. If you want to get into it, here is one place to start (there are many others on SO, too). But if you're just getting into PHP, I'd say using the global variable is fine.
The variable $db is not known within your function.

Categories