dpqmu84646 2014-04-20 00:00
浏览 26
已采纳

PDO的新手努力将我的结果的id变为变量

My problem is im querying to get the id from the row on a login request and set $_SESSION name to the id of that row, but im unsure on how to fetch that properly as my usual method doesn't seem to be working.

So im trying ..

if (isset($_POST['username']) && ($_POST['password'])) {
$username = trim($_POST['username']);
$username = strtolower($username);
$password = trim($_POST['password']);
$password= hash('sha256', $password);
$stmt = $dbh->prepare("SELECT `id` FROM `1_users` WHERE username=? AND password=? LIMIT 1");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->rowCount();
if ($row) {
// Match
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['user'] = $result['id'];
$_SESSION['logged_in'] = TRUE;
$_SESSION['ip'] = hash('sha1', "{$_SERVER['REMOTE_ADDR']}");
echo $result['id'];
//header ("location: staff.php");
}

unfortunatly $result['id'] is erroring as a undefinded index.. and echo $result['id']; is not outputting anything. but I know the row was found so what am I doing wrong when trying to get the id of that row into a variable?

  • 写回答

2条回答 默认 最新

  • doudi1750 2014-04-20 00:11
    关注

    So fetchAll() returns an array of rows (even if there is only one) that are themselves an array of columns, so you need:

    $_SESSION['user'] = $result[0]['id'];
    

    Or as mentioned in the comments use fetch():

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

    Which returns one row as an array of columns, then this will work:

    $_SESSION['user'] = $result['id'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。