Home > Software engineering >  PDO not fetching results returns an array of size 1
PDO not fetching results returns an array of size 1

Time:07-26

Simple selection of two columns:

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $conn->prepare("SELECT email, pasword FROM users");
  $stmt->execute();

  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

This does not work

  echo $result["email"];

Rest of the query

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}
$conn = null;

When I echo $result["email"] it does not echo anything. I tried to echo the size of the $result array and it said it was a size of 1.

CodePudding user response:

The $result variable contains an associative array, most likely you should use an iteration foreach, for, while, to get values. For example:

foreach($data as $result)
{
    $email = $data["email"];
}

If you want access to value without loop, try this:

$email = $result[0]["email"];

CodePudding user response:

you don't seem to be using the correct method to get the result. try this...

$result = $stmt->fetch(PDO::FETCH_ASSOC);

instead of this...

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

  • Related