代码之家  ›  专栏  ›  技术社区  ›  Chris

使用PDO获取单行、单列

  •  24
  • Chris  · 技术社区  · 16 年前

    "SELECT some_col_name FROM table_name WHERE user=:user"
    

    在我执行语句之后 $stmt->execute(); 如何将单个单元格直接放入没有循环的变量中?换句话说,如何获得

    from $stmt->execute();
    
    to $col_value = 100;
    

    $col_value = $stmt->fetchColumn();
    $col_value = $stmt->fetchColumn(0);
    

    正如你所看到的,我正试图用尽可能少的行数来做这件事。

    5 回复  |  直到 16 年前
        1
  •  38
  •   Dharman vijay    5 年前

    你确定它会返回任何行吗?

    $stmt->fetchColumn()
    

    是获取单个值的正确方法,因此您可能没有绑定:user参数,或者它没有返回任何行。

        2
  •  12
  •   JAL    16 年前
    $sql='SELECT some_col_name FROM table_name WHERE user=?';
    
    $sth=$pdo_dbh->prepare($sql);
    $data=array($user);
    
    $sth->execute($data);
    
    $result=$sth->fetchColumn();
    
        3
  •  1
  •   Matthew    9 年前

    我不知道为什么这么多人把事情搞砸了:

    $stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where"); 
    $stmt->bindValue(':where', $MyWhere);
    $stmt->execute();
    $SingleVar = $stmt->fetchColumn();
    

    确保您选择的是特定的 column * 或者,您需要在中指定列顺序号 fetchColumn() ,例如: $stmt->fetchColumn(2);

    这只会在以下情况下正常工作: unique 'wheres' ; fetchColumn()

        4
  •  1
  •   Cold Pen    6 年前

    要获取最后一次插入,请将DESC Limit 1添加到sql语句中。

    $sql = "SELECT `some_col_name` FROM table_name\n"
    
        . "ORDER BY `some_col_name` DESC\n"
    
        . "LIMIT 1";
    
    $stmt = $conn->prepare($sql);
    $result = $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    //convert the array content to string and store in variable 
    $col = implode(" ", $row);
    echo $col;
    
        5
  •  0
  •   True Soft    16 年前

    你先准备好声明了吗(之前 $stmt->execute() )

    $stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
    
        6
  •  0
  •   Joel keshlam    12 年前

    $stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);