How to get first row of data in sqlite3 using php PDO

爷,独闯天下 提交于 2019-12-23 20:22:41

问题


How to get first row of data in sqlite3 using php PDO

As per my below code first row data does not display becuase I have used recordset for check row is return or not.

Any idea how to get all data from record set?

My Code.

    try {
        $dbhandle = new PDO("sqlite:".$database);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }

    $result=$dbhandle->query("select * from table");

    if($result)
    {
        if($rs1==$result->fetchColumn())
        {
            while ($rs1 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) 
            {
                echo "<pre>";
                print_r($rs1);
                echo "</pre>";
            }
        }
        else
        {
            // error message
        }
}

回答1:


If you just want to get the first row, then there's no need to use a loop.

$result=$dbhandle->query("select * from table");
if ($result) {
  $row = $result->fetch(PDO::FETCH_ASSOC);
  echo "<pre>";
  print_r($row);
  echo "</pre>";
}

Update: For get all rows.

$result=$dbhandle->query("select * from table");
$rows = array();
if ($result) {
  while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
     $rows[] = $row;
  }
  if ($rows) {
     echo "<pre>";
     print_r($rows);
     echo "</pre>";
  } else {
     echo "No results";
  }
}


来源:https://stackoverflow.com/questions/12170785/how-to-get-first-row-of-data-in-sqlite3-using-php-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!