duanlu6268 2015-08-08 13:14
浏览 22
已采纳

数据库查询未按预期返回php pdo

Hi I am trying to query a database using pdo in php to return all of the information in my database, I am connecting properly to the database however when I try to return all of the database information and print it I get this result returned from my function >

PDOStatement Object ( [queryString] => SELECT * FROM users )

I would like for the function to return the entire database information. Here is my code, your help would be greatly appreciated, thank you.

  public function resetpassword() 
  {

         try
         {
            $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
            $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $sql = 'SELECT * FROM users';

            $result = $conn->query($sql);

            return $result;

            $conn = null;
         }
        catch(PDOException $e)
        {
            return 'Database Error';
        }

     }

here is the code I use to print the results from that function:

print_r ($usr->resetpassword());
  • 写回答

1条回答 默认 最新

  • duanke8011 2015-08-08 13:26
    关注

    $result is result set as PDOStatement object. If you use fetchAll() it will fetch data as an array of data. Although you can loop through PDOStatement object result set and extract data. Like this:

    foreach ($conn->query($sql) as $row) {
     echo $row['yourColumnName'];
    }
    

    Try this:

        <?php
    
        class Database{
    
        public function resetpassword() 
          {
    
                 try
                 {
                    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
                    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                    $sql = 'SELECT * FROM users';
    
                    $s = $conn->query($sql);
    
                    return $s->fetchAll(PDO::FETCH_ASSOC);
    
                    $conn = null;
                 }
                catch(PDOException $e)
                {
                    return 'Database Error';
                }
    
            }
    
        }
    
        $usr=new Database();
    
        var_dump($usr->resetpassword());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动