This code prints out a list of column names. But I would expect it to print out the information stored in the UserName table for the user with the LoginName of JSmith.
$loginname = "JSmith";
$stmt = $dbh->prepare("SELECT * FROM UserName WHERE LoginName=:login_name");
$stmt->bindValue(":login_name", $login_name, PDO::PARAM_STR);
$stmt->execute();
echo "<table><tr>";
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
foreach ($result as $key => $val){
echo "<th>" . $key . "</th>";
}
echo "</tr>";
echo "</table>";
Why doesn’t this return the row with the users name? Looking at echo gettype($result) shows me that they are strings and integers; not like each piece of the returned array is itself an array. I’m sure it’s a simple thing, but any help is appreciated. Thanks!
You’re printing the keys, not the values. The keys are the column names, and the values are the corresponding column values.
print_r($result)shows that$stmt->fetch()returns an array with the information you expect, and the corresponding HTML simply doesn’t reflect that.http://php.net/manual/en/pdostatement.fetch.php#example-1018
Let’s fix it.