I'm beginning with PHP and i need your help.
I create a try to list all members who has the same interest that the current_member( i mean the connected member ).
I write this :
$current_members = params('current_member');
$members_all = option('db')->query('SELECT * FROM members WHERE interest = $current_members["interest"] ORDER BY lastname, firstname')->fetchAll();
set('members_all', $members_all);
When I go on my page I have the error :
Fatal error: Call to a member function fetchAll() on a non-object
And in my view I just write this :
<h2 id="member-<?= $member['id'] ?>">
<?= avatar_tag($member,'30x30') ?>
<?=$member['firstname']?><small> <?= $member['lastname'] ?></small>
</h2>
I dont understand this error, anyone can help me ?
Thank's for your help.
Do not chain calls to query() and fetchAll() like you are doing. That's bad practice. Never assume your query worked, always check to see if it did.
$db = option('db');
$query = $db->query('SELECT ...');
if($query === FALSE){
print_r($db->errorInfo());
die;
}
$members_all = $query->fetchAll();
(Since you are calling fetchAll(), I assume you are using PDO (and not MySQLi))
Also, do not try to concatenate variables into your SQL query. (P.S. You're not even doing that, you are using single quotes, so $current_members["interest"] is not being read as a variable) That's just asking for an SQL injection attack. What you want to do is use prepared statements.
$db = option('db');
$query = $db->prepare('SELECT * FROM members WHERE interest = ? ORDER BY lastname, firstname');
$exec = $query->execute(array($current_members['interest']));
if($exec === FALSE){
print_r($query->errorInfo());
die;
}
$members_all = $query->fetchAll();
The "call to a member function on a non-object" error, means that you are trying to call a method on a variable that does not represent an object.
You have the following methods called one after the other on the $members_all denifition:
option('db')->query("...")->fetchAll();
You call the method "query" of whatever returns option('db') with some SQL query, and then you call fetchAll() method to whatever returns that "query" method.
I do not know if I explained myself well, the main point is that when you execute the query method it is returning something that has not the "fetchAll" method, in your case your SQL is wrong and probably query() is returning NULL or FALSE instead of a result set.
Change your single quotes with double quotes or concatenate the $current_member['interest'] variable.
IN your sql query
'SELECT * FROM members WHERE interest = $current_members["interest"] ORDER BY lastname, firstname'
you are using single quotes, so $current_members["interest"] actually does not resolve to a PHP variable, it is a string. You can switch single and double quotes:
Made an edit here, passing array offset was not fortunate:
$interest = $current_members['interest'];
"SELECT * FROM members WHERE interest = $interest ORDER BY lastname, firstname"
Unfortunately you did not share any of the underlying database code, but assuming option('db') is a pdo object, this should work fine.
If option('db') really is a pdo, before executing any statement add:
option('db') -> setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
this will tell you the exact error
Related
I am trying to execute a MySQL Stored Procedure using PDO connection, i tried almost everything but not able to execute it.
The SP will only insert and update. Following is the codes I tried till now.
$config = require('protected/config/main.php');
try
{
$db_adat = new PDO($config['components']['db']['connectionString'], $config['components'] ['db']['username'], $config['components']['db']['password']);
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
I tried with only fetch(), with only fetchAll(), fetchObject(), with fetch(PDO::FETCH_ASSOC), with fetchAll(\PDO::FETCH_ASSOC), but I always get following error
Fatal error: Call to a member function fetchAll() on a non-object in D:\ADAT_System\www\test\protected\controllers\ExportPDVController.php on line 35
I also tried using query() instead of execute(), but that doesn't work either.
I also tried adding a (select * ) statement in SP and tried with all above "fetch" options, but got same error.
The SP takes 7 minutes to complete, but all gave error immediately, so I am guessing it never ran the SP.
I tried as following too
$result= $this->$db_adat->prepare("CALL pdv()");
$result->execute();
but the I got following error:
Object of class PDO could not be converted to string
I am not passing any parameters in SP, just a simple call. Please let me know if any more information is required.
This part of your code is wrong
$result= $db_adat->prepare('CALL pdv()');
$a = $result->execute();
$a->fetchAll(PDO::FETCH_ASSOC);
Because execute() returns a boolean upon success or failure.
You cannot use that to fetch.here is the proper way with appropriate variable names:
$stmt= $db_adat->prepare('CALL pdv()');
$success = $stmt->execute();
if($success){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}else{
echo 'failed to run sp';
}
<?php
if(isset($_POST) && !empty($_POST)){
$SearchPO = (($_POST)['SearchPO']);
}
$stmt = $pdo->prepare("CALL spPO(?)");
$stmt->bindParam(1, $SearchPO, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT|PDO::ATTR_EMULATE_PREPARES, 4000);
$stmt->execute();
do {
$result = $stmt->fetchAll();
} while ($stmt->nextRowset() && $stmt->columnCount());
?>
You must use the nextRowset() function because the next record is 'empty' without it. Source
I used PDO hundreds of times but now I'm very frustrated - everything seems ok for me, I must be missing something... I use PGSql and PDO. Passing query to PgAdmin 3 and running it - no problem! But calling it from PDO is a different story.
My code:
(...checking if $name is null and so on...)
$query = "SELECT
*
FROM
out.city
WHERE
city_name ILIKE ?";
$stmt = $this->db->prepare($query);
try{
$res = $stmt->execute(array("'".$name."'"));
$ret = $res->fetchAll(PDO::FETCH_ASSOC);
(... rest of try-catch block...)
Problem is that $res returns boolean (true) instead of object. It results in error:
PHP Fatal error: Call to a member function fetchAll() on a non-object
I've tried few methods of how to put $name inside query - using question mark, bind or just joining the strings (I know, bad way). None of them work.
Should be prepare handle (object) only, replace $res-> with $stmt->,
$stmt->fetchAll(PDO::FETCH_ASSOC);
I'm trying to get simple info from a database and echo it to screen, but it's not working for me.
$con=mysqli_connect("SERVER.COM","USERNAME","PASSWORD", "DATABASE");
function GetTeamFixtures($team)
{
$queryget = mysqli_query($con, "SELECT * FROM 'mlsfixtures' WHERE team='$team' LIMIT 1");
$row = mysqli_fetch_assoc($queryget);
$gw1 = $row['gw1'];
$gw2 = $row['gw2'];
echo $team.' '.$gw1.' '.$gw2.'<br>';
}
$team = "Chicago Fire"; GetTeamFixtures($team);
$team = "Chivas USA"; GetTeamFixtures($team);
$team = "Colorado Rapids"; GetTeamFixtures($team);
//continue for all teams - removed for simplicity
Here are the error messages I get (line 46 is the $queryget= one and line 49 is the $row = one).
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in server.com\teamfix.php on line 46
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in server.com\teamfix.php on line 49
Any idea why? I'm not sure if there's an easier way of doing the same thing but for 19 different teams.
One of the errors i've found, aside from the two users that explained about connection, is the invalid use of single quotes.
Tables names should not be wrap with single quotes as they are identifiers and not a string literals. Remove the single quotes and it should work,
SELECT * FROM mlsfixtures WHERE team='$team' LIMIT 1
MySQL - when to use single quotes, double quotes, and backticks?
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Another way to access variables outside a function instead of using global variables is to add it up in its parameters
E.g
function GetTeamFixtures($team,$con)
{
// query inside
}
Also as J W says in your query remove '' or replace it with `` backticks..
(This is my attempt at combining all the other answers in a concise manner.)
There are two problems.
First, the global variable $con is not accessible from within your function without a global statement. The global statement can be used to create a reference to $con from within your function.
global $con; // is equivalent to:
$con =& $GLOBALS['con'];
Second, the table name cannot be enclosed in single quotes. Remove the quotes.
// By the way, this should be using mysqli::prepare and mysqli_stmt::bind_param
// to prevent SQL injection
$queryget = mysqli_query($con, "SELECT * FROM mlsfixtures WHERE team='$team' LIMIT 1");
You don't have access to $con from within your function. This should work:
$con = mysqli_connect("SERVER.COM","USERNAME","PASSWORD", "DATABASE");
function GetTeamFixtures($team)
{
global $con;
$queryget = mysqli_query($con, "SELECT * FROM `mlsfixtures` WHERE `team`='$team' LIMIT 1");
$row = mysqli_fetch_assoc($queryget);
$gw1 = $row['gw1'];
$gw2 = $row['gw2'];
echo $team.' '.$gw1.' '.$gw2.'<br>';
}
P.S. If the $team you're passing in to GetTeamFixtures comes from user input, you should prepare your statement, to prevent SQL injection.
$con isn't visible within the function. If you want a global variable to be in scope in a function, you must declare it global:
function GetTeamFixtures($team) {
global $con;
# ...
}
I am writing my PHP blog engine. I am using PDO for it. And now, when I am writing class Member - I have an error.
Fatal error: Call to a member function fetch() on a non-object in
/home/tucnak/Server/scripts/php/classes/Member.php on line 42
And source code of my Class:
public function authMember($user, $password)
{
$password = hashIt($password);
$count = 100500;
$count = $this->db->query("SELECT count(*) FROM users-general WHERE nick = $user AND password = $password;")->fetch();
echo($count);
// if ($count == 1){ return 1; } else { throw new Exception("",491); }
}
I have an error using this function.
Your query probably fails because you don't have quotes wrapped around your query.
When that happens, query() will return false instead of an object, breaking the chain.
Don't do it this way; run the query first, save its result, then check whether it's false.
By the way, you should really use prepared statements - your current statement is vulnerable to SQL injection.
"SELECT count(*) FROM `users-general` WHERE nick = '$user' AND password = '$password'"
note the single quotes of 2 different types
Thought, your misunderstanding has nothing to do with PDO. it's basic SQL syntax you have to learn
I created this code:
$statement = $db->prepare("SELECT * FROM phptech_contact");
$statement->execute();
$result = $statement->result_metadata();
$object = $result->fetch_object();
print_r( $object );
When I run it, it doesn't work. Can anybody tell me why it doesn't work?
I have 20 rows in this table so data should be returned.
From http://ch.php.net/manual/en/mysqli-stmt.result-metadata.php
Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().
As long as you don't need this meta data you don't need to call this method.
$statement = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$statement->execute();
$stmt->bind_result($fld1, $fld2);
while ($stmt->fetch()) {
echo "$fld1 and $fld2<br />";
}
But I really dislike the mysqli extension. PDO is much cooler ... ;-)
$db = new PDO('...');
$stmt = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$stmt->execute();
while ($obj = $stmt->fetchObject()) {
// ...
}
or
$objs = stmt->fetchAll(PDO::FETCH_OBJ);
if you're trying to get the rows from the database, the function you need is mysqli_stmt::fetch(), not mysqli_stmt::fetch_metadata()
You're also missing a few steps. When using prepared statements, you must specify the fields you would like to return instead of using the star wildcard, and then use mysqli_stmt::bind_result() to specify which variables the database fields should be placed in.
If you're more familiar with the original MySQL extension, prepared statements have a different process to use. If your select statement has a parameter (eg., "WHERE value=?") prepared statements are definitely recommended, but for your simple query, mysqli:query() would be sufficient, and not very different from the process of mysql_query()
I believe the problem is that mysqli_stmt::result_metadata() returns a mysqli_result object without any of the actual results — it only holds metadata.
So what you want to do is use $result = $statement->bind_result(...) and then call $result->fetch() repeatedly to get the results.
One of the comments under the bind-result() article shows how to do this for a query like yours, where you don't necessarily know all of the columns being returned.