Page 1 of 1

Force variable types in php or mysql

Posted: Mon Mar 05, 2007 3:53 pm
by shiznatix
In my framework I am starting to write in the ability to define a variable type and length for the variables that will be put into a query and then into a mysql database. My question is: is this even worth it or should I let mysql just do it all for me? I am already doing a variable type so that if its an id and they try to make it a string then it wont go into the db, it will just stay as 'null'.

Example, a sample Model class for my index looks like this:

Code: Select all

<?php

class indexModel extends modelBase
{
    public $id = array(
        'value' => null,
        'type'  => 'int',
    );

    public $name = array(
        'value' => null,
        'type'  => 'string',
    );

    public $_table = 'nfw2_index';
}

?>
and those variables 'value' can only be of that datatype. Also is that even worth it either or should I let mysql just do its own error checking and whatnot. I am also thinking about adding in the 'length' part there like I mentioned earlier.

I feel shady trusting security like that on a third party program (mysql) and hoping that it deals with everything properly. Am I just being too worrisome or is this a good step to forcing datatypes like other languages do?

Posted: Mon Mar 05, 2007 4:01 pm
by Begby
Its not a bad idea to do some error checking so that you can inform the user if they entered bad data or throw an exception as necessary, but I don't think that just putting in null values is the best solution. What if the database records depend on a key being inserted and you misccode something and it ends up getting inserted as a null everywhere?

As far as security goes though you might want to look into PDO prepared statements if you have php 5 or PEAR DB. No need to reinvent the wheel.

Posted: Mon Mar 05, 2007 5:03 pm
by Xoligy
If you wish to display your own user-friendly errors than it's worth it, but otherwise MySQL will do it for you anyway. Since it's a framework that a developer is supposed to build on, than that extra error checking isn't really necessary IMO.

Posted: Tue Mar 06, 2007 5:27 am
by Maugrim_The_Reaper
It's a bit redundant, but it can add some better user friendly errors. Likely the main reason you'd add it. At the end of the day, if you are using PDO or an object oriented abstraction layer for your database you'll end up receiving Exceptions when the database doesn't like your queries which can often have a similar, though obviously less informed, effect. I'm not sure how useful type detection is though - it's confusing enough validating user data which would typically catch such obvious issues so I suppose the usefulness aspect is one of context also. Not all data going into the database will be sourced from an untrusted user.