-2

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)){
Sumsar
  • 135
  • 1
  • 9

1 Answers1

1

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();
Bojangles
  • 99,427
  • 50
  • 170
  • 208
Jeremy Kendall
  • 2,869
  • 17
  • 17