简体   繁体   English

将TINYINT(1)转换为字符串

[英]Converting TINYINT(1) to a string

I want to convert a TINYINT(1) value to string. 我想将TINYINT(1)值转换为字符串。 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. 假设如果订阅的付费等于1(或true),那么当我从MySQL数据库中将值检索到.php文件时,结果将为“是”。 If subscription paid = 0 (or false) the the outcome will be "no". 如果订阅的paid = 0 (或否),则结果为“否”。

Is there a way to convert a TINYINT(1) value to a string containing my words of choice? 有没有一种方法可以将TINYINT(1)值转换为包含我选择的单词的字符串?

I am sorry if I am being indirect or if more information about the issue is required 很抱歉,如果我是间接人员,或者需要更多有关此问题的信息

You can use an IF : 您可以使用IF

SELECT IF(`column` = 1, 'yes', 'no') FROM `table_name`

Or: 要么:

SELECT IF(`column` = 0, 'no', 'yes') FROM `table_name`

Or you can use < or > etc. based on the data. 或者,您可以根据数据使用<>等。

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: 鉴于MySQL没有提供任何体面的机制来防止在TINYINT列中插入-133 ,因此我将简单地针对零/非零进行测试:

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 . 这个问题也被标记为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. 在显示时获取正确的字符串应该很简单。

You can do this in PHP: 您可以在PHP中执行此操作:

$number = 1; // or 0 - basically your MySQL variable
$word = $number ? "yes" : "no";

Alternatively, do it in your MySQL query: 或者,在您的MySQL查询中执行此操作:

SELECT IF(`column_name` = 1, 'yes', 'no') FROM ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM