0

Please help me in this code, I don't know why this is drop this error:

Fatal error: Call to a member function fetchAll() on a non-object in D:\Users\Felhasznalo\Desktop\xamppa\htdocs\dart\throwMap.php on line 7

And here is my code:

$p = $_GET['player'];
$pdo = new PDO('mysql:dbname=dart;host=127.0.0.1', 'root', '');
$query = $pdo->prepare("SELECT * FROM dart WHERE player={$p}");
$query = $query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
5
  • Your prepare() call failed. You need to configure PDO to throw exceptions, otherwise it errors silently (and causes things like this) $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Then work on binding $p correctly as a placeholder parameter. Commented Dec 22, 2014 at 21:25
  • You need to be using $pdo->prepare("SELECT * FROM dart WHERE player=:player"); and $query->execute(array(':player' => $p)); Commented Dec 22, 2014 at 21:26
  • 1
    @MichaelBerkowski Are you sure? If the prepare fails the execute statement should be throwing the error. I believe the OP is overwriting the prepared statement with the next line $query = $query->execute(). This overwrites $query with the boolean return value of true or false from the execute statement causing the error when fetchAll() is called on the boolean. Commented Dec 22, 2014 at 21:26
  • @War10ck Yes, the overwrite is what's actually causing the error here (maybe, unless $p is a string which isn't quoted) but the much bigger issue is the use of $p directly. Commented Dec 22, 2014 at 21:28
  • @MichaelBerkowski Ah, ok that part makes sense. I was a little confused by the first comment. I see what you mean now. It doesn't help to prepare a statement if you're going to inject the user input into the prepare and not the execute. That is a problem for sure. The existing problem is the overwrite though, not the prepare. Commented Dec 22, 2014 at 21:29

1 Answer 1

3

Change this:

$query = $query->execute();

to just this:

$query->execute();

(You don't need to re-assign the query var)

http://php.net/manual/en/pdostatement.execute.php#example-994

Also, please use PDO bindings to protect your app from injection attacks:

$query = $pdo->prepare("SELECT * FROM dart WHERE player=:player");
$query->execute(array(':player' => $p));
$result = $query->fetchAll(PDO::FETCH_OBJ);
Sign up to request clarification or add additional context in comments.

2 Comments

You should expand this answer to incorporate the placeholder binding currently missing from the code. Otherwise, it remains SQL injection vulnerable and there's no value to using prepare()/execute()
(and I placed it back in context of the OP's variable assignments)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.