【问题标题】:How to get name from id in array using query?如何使用查询从数组中的 id 获取名称?
【发布时间】:2017-07-12 08:56:43
【问题描述】:

我有数组值作为原因

例如:$cause = $_REQUEST['cause'];

即,$cause = 2,3,4

如何从查询中获取该数组值原因名称

我的表名是'cp_cause'

如何从上表中得到2,3,4的原因名称。

我在 thinkphp 中的示例查询模型是

$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id = '".$cause."'");

我想要劳动力、健康、女性的名称

【问题讨论】:

  • 你问怎么办WHERE id IN (2,3,4)
  • 我有 2,3,4,但我只希望 ids 名称像 labour,health,women

标签: php mysql thinkphp


【解决方案1】:

如果我猜对了:你得到逗号分隔的 ID 并想查询这个?

SELECT * FROM cp_cause WHERE id IN (2, 3, 4)

PHP:

$cpCauses = $GLOBALS['db']->getAll("select * from cp_cause where id in('".$cause."')");

结果应该是一个列表,包含匹配的行。但我们不知道,您的 getAll-Method 会返回什么!

例子:如果result是一个数组,你可以迭代:

foreach($cpCauses as $cause) {
    echo $cause['cause_name'];
}

【讨论】:

  • 非常感谢,谢谢@BenRoob
【解决方案2】:

您需要创建类似'2','3','4' 的字符串,以便使用MySql in 子句进行检查。

例如

<?php
    $cause = array();
    $cause[] = '2';
    $cause[] = '3';
    $cause[] = '4';
    $sql_where = array(); 
    foreach($cause as $values){
        $sql_where[] = "'".$values."'";
    }
    $sql_where = implode(",",$sql_where);
    $cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id in '".$sql_where."'");
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2023-03-27
    • 2020-02-08
    • 2021-08-29
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多