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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件