Webeng Webeng - 6 months ago 27
MySQL Question

shorthand PDO query

Currently to perform a query with PDO, I use the following lines of code:

$sql = "SELECT * FROM myTable WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);


And after some research, I found a shorter way of executing the same command:

$stmt_test = $conn->prepare("SELECT * FROM status WHERE status_id = ?");
$stmt_test->execute([$id])->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt_test->fetchAll(PDO::FETCH_ASSOC);


From there I thought I could possibly make it even shorter with the following code:

$stmt_test = $conn->prepare("SELECT * FROM status WHERE status_id = ?");
$result = $stmt_test->execute([$id])->fetchAll(PDO::FETCH_ASSOC);


But I get the following error:


Fatal error: Call to a member function fetchAll() on a non-object in
/home/.../index.php on line 20


QUESTION: Why am I getting this error? From my understanding,
$stmt_test->execute([$id])
should be executing first, then the result of that would execute the
->fetchAll(PDO::FETCH_ASSOC)
and from there return the array to
$result
, but since the error is happening, something must be flawed in my logic. What am I doing wrong? Also, does anyone know a better shorthand method to perform the previous query?

Answer

$stmt_test->execute([$id]) returns a boolean value. That mean that

$result = $stmt_test->execute([$id])->fetchAll(PDO::FETCH_ASSOC);

isn't valid. Instead you should do

$stmt_test->execute([$id]);
$result = $stmt_test->fetchAll(PDO::FETCH_ASSOC);
Comments