Search code examples
phpmysqlstringtinyint

Converting TINYINT(1) to a string


I want to convert a TINYINT(1) value to string. Let's say if subscription paid is equal to 1 (or true) then the outcome will be "yes" when I retrieve the value from my MySQL database to my .php file. If subscription paid = 0 (or false) the the outcome will be "no".

Is there a way to convert a TINYINT(1) value to a string containing my words of choice?

I am sorry if I am being indirect or if more information about the issue is required


Solution

  • Given that MySQL does not provide any decent mechanism to prevent inserting -1 or 33 into a TINYINT column, I'd simply test against zero/non-zero:

    SELECT CASE
        WHEN paid<>0 THEN 'Yes'
        WHEN paid=0 THEN 'No'
        ELSE 'Unknown'
    END is_paid
    FROM suscription
    

    The question is also tagged as PHP. I think it's cleaner to use native types as much as possible:

    if (is_null($row['paid']) {
        $paid = null;
    }else{
        $paid = $row['paid']!=0;
    }
    

    Getting the right string when displaying should be straightforward.