oldboy
oldboy

Reputation: 5954

Combining two prepared statements not working

First, according to another SO post, I tried combining the two statements into one.

<?php
  $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
  $sql  = "UPDATE users SET pass = :password WHERE usrn = :id;
           SELECT prim FROM users WHERE usrn = :id;";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(":id", $_SESSION["idPersist"]);
  $stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
  $stmt->execute();
  $result = $stmt->fetch(PDO::FETCH_ASSOC); //// line 71
?>

However, this kept throwing the error: Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error on line 71.

I couldn't find any relevant solutions to this issue, so I decided to simply split up the two statements.

<?php
  $sql  = "UPDATE users SET pass = :password WHERE usrn = :id";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(":id", $_SESSION["idPersist"]);
  $stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
  $stmt->execute();
  $sql  = "SELECT prim FROM users WHERE usrn = :id";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(":id", $_SESSION["idPersist"]);
  $stmt->execute();
  $result = $stmt->fetch(PDO::FETCH_ASSOC);
  $_SESSION["session"] = $result["prim"];
?>

But a var_dump($result) is returning Bool(false), so obviously something is not working right with fetching the result and storing it as a variable, it seems, in both cases.

I'm new to PHP and MySQL, so I'm at a loss right now.

Upvotes: 0

Views: 54

Answers (1)

S4NDM4N
S4NDM4N

Reputation: 924

Change this,

$sql  = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];

To this,

$sql  = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute(); // Your problem
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];

You are missing the execution of the query.

Upvotes: 1

Related Questions