php - 如何获取MySQL int字段的长度

标签 php mysql pdo

我有一个 MySQL 表,其中包含不同长度的 int 字段:

MySql mediumint and tinyint fields of different lenght

如何找出长度(nav_parent = 4, nav_show = 2, nav_order = 2) 使用 PHP PDO?

最佳答案

这在 MySQL 中有效并且不是实验性的:

 $result = $this->query('SHOW COLUMNS FROM your_table_name', PDO::FETCH_ASSOC);

现在你有以下信息:

[Field] => yourfieldname
[Type] => int(10)
[Null] => NO
[Key] => PRI
[Default] => 
[Extra] => auto_increment

你可以像 [Type] => int(10) 那样提取长度形式

preg_match('/\d+/', $col['Type'], $len); // gives you the number

整个例子:

$result = $pdo->query('SHOW COLUMNS FROM youTableName');

$columLen = array();

foreach($result as $key => $col){

  preg_match('/\d+/', $col['Type'], $len); // get the number out of 'int(10)'
  $len = (isset($len[0]))? $len[0] : '';   // is there a length? 
  $fieldname = $col['Field'];              // name of the column
  $columLen[$fieldname]  = $len;           // save it in array 
}

print_r($columLen);

输出:

Array
(
  [nav_parent] => 4
  [nav_show] => 1
  [nav_order] => 2
)

注意: 某些字段类型,如日期、日期时间或文本不会显示值长度。 示例:时间戳类型的字段将显示 "[Type] => timestamp" 而不是 "[Type] => timestamp (12)"

关于php - 如何获取MySQL int字段的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20146561/

相关文章:

php - 使用 PDO-MYSQL 准备语句进行多次插入时,将 NOW() 函数作为非字符串传递?

链接表的 PHP Mapper 模式

mysql - Grail 集成测试用例是否将数据提交到数据库

php - magento 将自定义输入字段添加到管理员中的客户帐户表单

php - Paypal 休息沙盒错误

sql - 有没有办法将 SQL 列与 LIKE 结合起来

PHP PDO + PostgreSQL - 事务处理

PHP/SQL/PDO 注册多个表(用户、详细信息)

php - phpurple编译错误-php 5.3

php - 是否可以使用 PHP CLI 获取 *.sh 文件并在 PHP 脚本中访问导出的环境变量?