Search code examples
phpmysqlpdofetchall

trying to check if string exist with PDO


I'm trying to check if a string exist in my database. but i keep getting this error message "Fatal error: Call to a member function fetch() on a non-object on line 8"

$string = random_string(30);

$sql = create_sql(); //returns a PDO object with connection to the database
$data = $sql->prepare("SELECT * FROM session WHERE string =:string");
$data->bindParam(':string', $string);
$data = $data->execute();

$row = $data->fetchAll();

if(empty($row)){

Solution

  • Your code uses fetchAll(), but the bug is pretty obvious. qwertynl's comment is correct - you're overwriting $data so afterwards it's not a PDOStatement object so you can't use the fetch() or fetchAll() methods.

    Update your code to the following and you should be good to go.

    $string = random_string(30);
    
    $sql = create_sql(); //returns a PDO object with connection to the database
    $stmt = $sql->prepare("SELECT * FROM session WHERE string =:string");
    $stmt->bindParam(':string', $string);
    $stmt->execute();
    
    $data = $stmt->fetchAll();