dousigan0499 2016-07-18 17:21
浏览 36
已采纳

如何在没有foreach或while的情况下获取mysqli中的assoc?

In mysql, we use

$userdata = mysql_fetch_assoc(mysql_query("select * tablename where id=".$_SESSION['user_id']."));

And then we can use $userdata anywhere on that page....

How can we do it with mysqli without using foreach or while statement ?

What I have tried is

<?
include ("db.php");
session_start();
if(isset($_SESSION['user_id']))
 {
   $userid = $_SESSION['user_id'];

   $query = "SELECT * FROM mytable where id= '$userid'";

   $userdataraw = $database->get_results($query);

   $userdata = $userdataraw ->fetch_assoc();
 }
?>

Class Used as :

public function get_results( $query, $object = false )
    {
    self::$counter++;
    //Overwrite the $row var to null
    $row = null;

    $results = $this->link->query( $query );
    if( $this->link->error )
    {
        $this->log_db_errors( $this->link->error, $query );
        return false;
    }
    else
    {
        $row = array();
        while( $r = ( !$object ) ? $results->fetch_assoc() : $results->fetch_object() )
        {
            $row[] = $r;
        }
        return $row;   
    }
}

When I tried This, I got error

Fatal error: Call to undefined function fetch_assoc()

I want set $userdata without foreach or while, is it possible in Mysqli??

  • 写回答

1条回答 默认 最新

  • dswmmvrg40957 2016-07-18 17:55
    关注

    The get_resultsfunction already returns an associative array if the second parameter is not set or false. Thus there is no need to call fetch_assoc() again.

    Also if you only expect a single dataset and don't want to use a loop you would need to do something like this: $userdata = $userdataraw[0]to get the first and only dataset.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击