Hkachhia
Hkachhia

Reputation: 4539

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

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
        }
}

Upvotes: 4

Views: 5907

Answers (1)

xdazz
xdazz

Reputation: 160833

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";
  }
}

Upvotes: 5

Related Questions