Search notes:

PHP code snippets: PDO statement class / sqlite

getColumnMeta()

getColumnMeta($col) returns an associative array for (0-indexed) column $col. The indexes of this array are
The following example tries to demonstrate how getColumnMeta() can be used to query a result set's column names and types.
Because SQLite is flexibly typed, a record's data type can only be determined after fetching it. Thus, in this example, $stmt->execute() was required for getColumnMeta() to return any meaningful data.
The example fetches two records and calls getColumnMeta() twice to demonstrate that it indeed does return different data types each time.
Finally, it seems that the blob data type is not recognized correctly. At least, I was unable to insert and/or get a blob.
<?php

$db = new PDO("sqlite::memory:");

$db->exec('create table T (
   col_1 integer,
   col_2 text,
   col_3 real,
   col_4 blob
)');

$db->exec("insert into T values (   1 , 'one', 1.1, 'xyz')");
$db->exec("insert into T values ('two', 2.2  ,   2, x'deadbeef')");

$stmt = $db->prepare('select * from T');
$stmt->execute();

$colCount = $stmt->columnCount();
print("Table has $colCount columns.<p>");

printMetaInfo($stmt);
printMetaInfo($stmt);

function printMetaInfo($stmt) {

   $colCount = $stmt->columnCount();

   $rec = $stmt->fetch();

   print("<hr><table border='1'>");
   print("<tr><td>Name</td><td>Type</td><td>Value</td></tr>\n");

   for ($col=0; $col < $colCount ; $col++) {
      $meta = $stmt->getColumnMeta($col);
      printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $meta['name'], $meta['native_type'], $rec[$meta['name']]);
   }

   print("</table>");
}


?>
Github repository about-php, path: /db/pdo/sqlite/statement/getColumnMeta.php

See also

PHP: Accessing an SQLite database with PDO

Index