基于MySQL列数据类型的动态PHP代码创建 [英] Dynamic PHP Code creation based on MySQL Column Data Types

查看:71
本文介绍了基于MySQL列数据类型的动态PHP代码创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一种工具,该工具可基于数据库中的表创建PHP类.大多数功能基于SHOW COLUMNS FROM $table中的数据.每列通常与正在创建的新类中的实例变量相关.

I am developing a tool that creates PHP classes based on tables in my database. Most of the functionality is based on data from SHOW COLUMNS FROM $table. Each column typically relates to an instance variable in the new class being created.

我现在遇到的情况是,如果用户为与INT类型的列相关的变量输入十二",它不会失败,但是数据库中的值将变为0.

What I have now is a situation where if a user passes in "twelve" for a variable related to a column of type INT, it doesn't fail, but the value in the database becomes 0.

我想让类返回false,表示无法完成UPDATEINSERT.

What I would like is for the class to return false, identifying that the UPDATE or INSERT could not be completed.

您会为此推荐什么方法?

我现在正在尝试的是构造一个列名称数组,其中包含具有数字数据类型(INT,FLOAT等)的每一列.当用户尝试设置变量时,它会检查该变量是否在此列表中,然后检查所设置的值以确定它是否为数字.

What I'm trying now, is to construct an array of column names that contains each column that has a numeric data type (INT, FLOAT etc.). And when the user tries to set a variable, it checks to see if the variable is in this list and then checks the value being set to determine if it is a number.

使用MySQLi的PHP 5.3.3

PHP 5.3.3 using MySQLi

我假设任何非数字列都将接受文本数据.

I'm assuming any column that isn't numeric will accept text data.

推荐答案

您在问什么叫ORM. PHP中有一些不错的ORM库.

What are you are asking is called ORM. There are some good ORM libraries in PHP.

  1. Doctrine
  2. 推进
  3. 插座ORM
  4. 为Kohana部署ORM (我使用了它)
  5. PHP数据映射器
  1. Doctrine
  2. Propel
  3. Outlet ORM
  4. Leap ORM for Kohana ( I use it )
  5. PHP Data Mapper

顺便说一句,我回答你的问题.

BTW, I answer your question.

如果设置了任何无效数据,则可以引发异常.

If any invalid data is set you can throw an Exception.

查看示例.

class MyTable extends DbTable{
    function __set($var, $val){
        switch($var){
            case 'age': // age should be numeric type
                if(!is_numeric($val)){
                    throw new InvalidDataTypeException("$val of $var is not numeric");
                }
             /// do other operation here

             ... 
             ... // more cases
        }
    }
}

这篇关于基于MySQL列数据类型的动态PHP代码创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆