AlexMp AlexMp - 7 months ago 8
PHP Question

Fatal error: Call to a member function prepare() on integer

I'm working on a website; apache asks me to upgrade to the new method of PDO.

I have my function which will collect all the information of user X, indicated by the variable $_SESSION['username'].

My problem is: I get the error title. However I want to collect String and INT values.

My Function: functions.php

function getDetails($username) {
$db = require("dbConn.php");
$sql = $db->prepare("SELECT * FROM `es42_members` WHERE HandleName='$username'");
$sql->execute();
$row = $sql->fetchAll();

return $row;
}


My index file: index.php

$details = getDetails($_SESSION['username']);

while ($row = $details->fetch_assoc()) {
$id = $row['UserID'];
$email = $row['Email']; // This return String
$isAdmin = $row['isAdmin']; //This return 0 - 1. But in the table is registered by String (Varchar).
}

echo "Your email is: $email";
if($isAdmin == "1"){ echo "You are a admin!" }


UPDATE
My new code is as follows:

Function: @Marcus

function getDetails($username) {
require("dbConn.php");
$sql = $db->prepare("SELECT * FROM `es42_members` WHERE HandleName='$username'");
$sql->execute();
$row = $sql->fetchAll();

return $row;
}


dbConn.php [Original]

<?php

$db = new PDO('mysql:host=localhost;dbname=ProfileTest', "root", "1234");
$db = null;

?>


dbConn.php [Edited and working]

<?php

$db = new PDO('mysql:host=localhost;dbname=ProfileTest', "root", "1234");

?>

Answer

This is happening because $db isn't actually holding the PDO connection object. You've assigned the dbConn.php script itself (returns 1 on successful inclusion) to $db, which is why you're receiving the integer error in question.

Your dbConn.php file should look something like the following (please add dbConn.php to your original post for verification):

// dbConn.php
$db = new PDO($dsn, $user, $password); // PDO has been instantiated and $db is holding the object

Then in your functions.php script:

function getDetails($username) {
    require("dbConn.php"); // require me, don't assign me to a variable
    $sql = $db->prepare("SELECT * FROM `es42_members` WHERE HandleName='$username'");
    $sql->execute();
    $row = $sql->fetchAll();

    return $row;
}

You'd simply require dbConn.php and NOT assign it to any variable.