John Davidson

php - How to get the data type of columns fetched across all PDO drivers?

0 comments
Message:


I am using the following (array_keys) to get column names from SQL statements:


$this_sql="select * from orders";
$stmt = $PDO->prepare($this_sql);
$stmt->execute();
$resultz = $stmt->fetch(PDO::FETCH_ASSOC);

foreach(array_keys($resultz) as $column_names)
{
echo $column_names;
}

Is there a similar way to get the datatypes of the columns? For instance: int, float, varchar, etc.?


I read about getColumnMeta but I also understand that does not work for all drivers.



My Answer:
One way to get the data types of columns fetched across all PDO drivers is to use the `getColumnMeta` method. However, as you mentioned, this method may not work for all drivers.

Here is an example of how you can use `getColumnMeta` to get the data types of columns:

php
$this_sql = "select * from orders";
$stmt = $PDO->prepare($this_sql);
$stmt->execute();
$resultz = $stmt->fetch(PDO::FETCH_ASSOC);

foreach(array_keys($resultz) as $column_names)
{
$meta = $stmt->getColumnMeta($column_names);
echo $column_names . " - " . $meta['native_type'] . "
";
}


The `getColumnMeta` method returns an array of meta information for a column, including the data type (`native_type`). This should work for most PDO drivers, but it's always a good idea to test it with your specific driver to ensure compatibility.

Rate this post

3 of 5 based on 7349 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us